Python,分析htm

2024-06-14 11:20:41 发布

您现在位置:Python中文网/ 问答频道 /正文

多亏了这个网站的热心用户,我对如何使用re作为非标准python模块的替代品有了一些想法,以便我的脚本能够以最小的挂起工作。今天,我一直在尝试解析模块。我遇到过美女。。这很好,但我不明白。在

出于教育目的,我想从http://yify-torrents.com/browse-movie中删除以下信息(请不要告诉我使用网络爬虫程序,我不是要爬网整个网站-只需从该页面中提取信息以了解解析模块是如何工作的!)在

电影片名 质量 Torrent链接

其中有22个项目,我希望它们按顺序存储在列表中,即项目1、项目2。这些清单需要包含这三项。例如:

item_1 = ["James Bond: Casino Royale (2006)", "720p", "http://yify-torrents.com/download/start/James_Bond_Casino_Royale_2006.torrent"]
item_2 = ["Pitch Perfect (2012)", "720p", "http://yify-torrents.com/download/start/Pitch_Perfect_2012.torrent"]

然后,为了简单起见,我只想把每一项都打印到控制台上。然而,更困难的是,这些项目在页面上没有标识符,因此信息。需要严格的命令。这一切都很好,但我得到的不是每个列表项包含的整个源,就是空的项!项目分隔符示例如下:

^{pr2}$

有什么想法吗?有人能赏光给我举个例子吗?我不确定靓汤能满足我的所有要求!抱歉,英语太差了,它不是我的第一语言。在


Tags: 模块项目com信息http列表网站页面
2条回答
from bs4 import BeautifulSoup
import urllib2

f=urllib2.urlopen('http://yify-torrents.com/browse-movie')
html=f.read()
soup=BeautifulSoup(html)


In [25]: for i in soup.findAll("div",{"class":"browse-info"}):
    ...:     name=i.find('a').text
    ...:     for x in i.findAll('b'):
    ...:         if x.text=="Quality:":
    ...:             quality=x.parent.text
    ...:     link=i.find('a',{"class":"std-btn-small mleft torrentDwl"})['href']
    ...:     print [name,quality,link]
    ...:     
[u'James Bond: Casino Royale (2006)', u'Quality: 720p', 'http://yify-torrents.com/download/start/James_Bond_Casino_Royale_2006.torrent']
[u'Pitch Perfect (2012)', u'Quality: 720p', 'http://yify-torrents.com/download/start/Pitch_Perfect_2012.torrent']
...

或者要获得您想要的输出:

^{pr2}$

根据您的要求,我粘贴了解析器的简单示例。如您所见,它使用lxml。对于lxml,有两种方法来处理DOM树,一种是xpath,另一种是css选择器 我更喜欢xpath。在

import lxml.html
import decimal
import urllib

def parse():
    url = 'https://sometotosite.com'
    doc = lxml.html.fromstring(urllib.urlopen(url).read())
    main_div = doc.xpath("//div[@id='line']")[0]
    main = {}
    tr = []
    for el in main_div.getchildren():
    if el.xpath("descendant::a[contains(@name,'tn')]/text()"):
        category = el.xpath("descendant::a[contains(@name,'tn')]/text()")[0]
        main[category] = ''
        tr = []
    else:
        for element in el.getchildren():
            if '&#8212' in lxml.html.tostring(element):
                tr.append(element)
                print category, tr
parse()

LXML official site

相关问题 更多 >