use*_*572 5 python regex beautifulsoup
我使用Beautiful Soup来提取特定的div标签,似乎我不能使用简单的字符串匹配.
该页面有一些标签形式
<div class="comment form new"...>
Run Code Online (Sandbox Code Playgroud)
我想忽略它,还有一些标签的形式
<div class="comment comment-xxxx...">
Run Code Online (Sandbox Code Playgroud)
其中x表示任意长度的整数,椭圆表示由空格分隔的任意数量的其他值(我不关心).我无法弄清楚正确的正则表达式,特别是因为我从未使用过python的re class.
运用
soup.find_all(class_="comment")
Run Code Online (Sandbox Code Playgroud)
查找以单词comment开头的所有标签.我试过用
soup.find_all(class_=re.compile(r'(comment)( )(comment)'))
soup.find_all(class_=re.compile(r'comment comment.*'))
Run Code Online (Sandbox Code Playgroud)
还有很多其他变种,但我想我在这里遗漏了一些关于正则表达式或match()如何工作的东西.谁能帮我吗?
aba*_*ert 15
我想我已经得到了它:
>>> [div['class'] for div in soup.find_all('div')]
[['comment', 'form', 'new'], ['comment', 'comment-xxxx...']]
Run Code Online (Sandbox Code Playgroud)
请注意,与BS3中的等效物不同,它不是这样的:
['comment form new', 'comment comment-xxxx...']
Run Code Online (Sandbox Code Playgroud)
这就是你的正则表达式无法匹配的原因.
但你可以匹配,例如:
>>> soup.find_all('div', class_=re.compile('comment-'))
[<div class="comment comment-xxxx..."></div>]
Run Code Online (Sandbox Code Playgroud)
请注意,BS相当于re.search,而不是re.match,因此您不需要'comment-.*'.当然,如果你想匹配,'comment-12345'但不是'comment-of-another-kind你想要的,例如,'comment-\d+'.
| 归档时间: |
|
| 查看次数: |
10464 次 |
| 最近记录: |