python - 使用 SoupStrainer 进行选择性解析

标签 python beautifulsoup scrape

我正在尝试解析来自购物网站的视频游戏名称列表。然而,因为项目列表都存储在一个标签内。
文档的 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,我会用一颗石头杀死2只鸟。
非常感谢。

最佳答案

哦,天哪,我是不是很傻,我正在搜索具有属性 ID = 产品的标签,但它应该是 product_list

如果有人来搜索,这里是最终代码。

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

关于python - 使用 SoupStrainer 进行选择性解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4004979/

相关文章:

python - 创建一个三维数据框(python)

python - 从文件中分段读取

python - 用 beautifulsoup 进行现场抓取

python - 用 Python 从许多 Google 搜索中抓取链接

Python CouchDB/httplib-错误 : [Errno 61] Connection refused

python - 如何在 BeautifulSoup4 中抓取结束标签旁边的文本?

css - Beautiful Soup 无法区分 CSS 类

python - 如何从 re.findall 中排除一个字符串?

php - 使用 PHP Simple HTML DOM Parser 卡住选择类或 id

python - 如何增加打印的每行新行的前导空格数?