使用SoupStrainer有选择地解析

2024-06-12 16:53:20 发布

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

我试图分析一个购物网站的视频游戏标题列表。但是,由于项目列表都存储在一个标记中。

文档的This部分可能解释了如何只解析文档的一部分,但我无法解决它。我的代码:

from BeautifulSoup import BeautifulSoup
import urllib
import re

url = "Some Shopping Site"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
for a in soup.findAll('a',{'title':re.compile('.+') }):
    print a.string

目前是在任何具有非空标题引用的标记中打印字符串。但它也在侧栏中列出了“特色菜”。如果我只能接受产品列表div,我将一石二鸟。

非常感谢。


Tags: 文档标记importre游戏url标题列表
2条回答

哦,天哪,我真傻,我在找atribute id=产品的标签,但应该是产品清单

如果有人来搜索,这是最后的代码。

from BeautifulSoup import BeautifulSoup, SoupStrainer
import urllib
import re


start = time.clock()
url = "http://someplace.com"
html = urllib.urlopen(url).read()
product = SoupStrainer('div',{'id': 'products_list'})
soup = BeautifulSoup(html,parseOnlyThese=product)
for a in soup.findAll('a',{'title':re.compile('.+') }):
      print a.string

尝试先搜索产品列表div,然后搜索具有标题的a标记:

product = soup.find('div',{'id': 'products'})
for a in product.findAll('a',{'title': re.compile('.+') }):
   print a.string

相关问题 更多 >