4

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

文档的这一部分应该解释了如何仅解析文档的一部分,但我无法解决。我的代码:

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

非常感谢。

4

2 回答 2

12

哦,天哪,我傻了,我正在搜索属性 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
于 2010-10-24T03:58:15.170 回答
0

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

product = soup.find('div',{'id': 'products'})
for a in product.findAll('a',{'title': re.compile('.+') }):
   print a.string
于 2010-10-23T17:58:04.427 回答