end*_*ith 40 python screen-scraping beautifulsoup
如果网页上有<div class="class1">
和<p class="class1">
,然后soup.findAll(True, 'class1')
就会发现他们两个.
<p class="class1 class2">
但是,如果它有,它将无法找到.如何找到具有某个类的所有对象,无论它们是否还有其他类?
end*_*ith 35
不幸的是,BeautifulSoup将此视为一个带有空格的类'class1 class2'
而不是两个类['class1','class2']
.解决方法是使用正则表达式来搜索类而不是字符串.
这有效:
soup.findAll(True, {'class': re.compile(r'\bclass1\b')})
Run Code Online (Sandbox Code Playgroud)
Kug*_*gel 18
以防任何人遇到这个问题.BeautifulSoup现在支持这个:
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
In [1]: import bs4
In [2]: soup = bs4.BeautifulSoup('<div class="foo bar"></div>')
In [3]: soup(attrs={'class': 'bar'})
Out[3]: [<div class="foo bar"></div>]
Run Code Online (Sandbox Code Playgroud)
此外,您不必再键入findAll.
aeh*_*lke 11
你应该使用lxml.它适用于由空格分隔的多个类值('class1 class2').
尽管它的名字,lxml也用于解析和抓取HTML.它比BeautifulSoup快得多,甚至比BeautifulSoup(他们声名鹊起)更能处理"破碎"的HTML.如果您不想学习lxml API,它也有BeautifulSoup的兼容性API.
Ian Bicking同意并且更喜欢lxml而不是BeautifulSoup.
没有理由再使用BeautifulSoup了,除非您使用的是Google App Engine或者其他任何不允许使用Python的东西.
你甚至可以使用带有lxml的CSS选择器,因此它比BeautifulSoup更容易使用.尝试在交互式Python控制台中使用它.
归档时间: |
|
查看次数: |
14348 次 |
最近记录: |