【问题标题】:Using SoupStrainer to parse selectively使用 SoupStrainer 进行选择性解析
【发布时间】:2010-10-23 16:34:31
【问题描述】:

我正在尝试解析来自购物网站的视频游戏标题列表。但是,由于项目列表都存储在标签内。

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只鸟。

非常感谢。

【问题讨论】:

    标签: python beautifulsoup scrape


    【解决方案1】:

    天哪,我傻了,我正在搜索属性 id = products 的标签,但它应该是 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
    

    【讨论】:

    • 在bs4中,现在是parse_only=
    【解决方案2】:

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

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

    【讨论】:

    • 试过了,但它给出了这个错误: Traceback (last recent call last): File "~/start.py", line 11, in for a in product.findAll('a' ,{'title':re.compile('.+') }): AttributeError: 'ResultSet' object has no attribute 'findAll'
    • 尝试调用soup.find 而不是soup.findAll
    • 不是它给我的,Traceback(最近一次调用最后一次):文件“~/src/start.py”,第 13 行,在 中 for a in product.findAll('a' ,{'title':re.compile('.+') }): AttributeError: 'NoneType' object has no attribute 'findAll'
    • 好的,我尝试实现过滤器,这就是我得到的,但它确实打印了任何东西(抱歉不确定如何在评论中换行) url = "somelink" html = urllib.urlopen (url).read() product = SoupStrainer('div',{'id': 'products'}) soup = BeautifulSoup(html,parseOnlyThese=product) for a in soup.findAll('a',{'title' :re.compile('.+') }): 打印一个.string
    猜你喜欢
    • 2012-01-02
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多