DrB*_*Bug 2 python regex beautifulsoup web-scraping
我在表单的 HTML 中有链接
<a href="/downloadsServlet?docid=abc" target="_blank">Report 1</a>
<a href="/downloadsServlet?docid=ixyz" target="_blank">Fetch Report 2 </a>
Run Code Online (Sandbox Code Playgroud)
我可以使用 BeautifulSoup 获取上述表单的链接列表
我的代码如下
from bs4 import BeautifulSoup
html_page = urllib2.urlopen(url)
soup = BeautifulSoup(html_page)
listOfLinks = list(soup.findall('a'))
Run Code Online (Sandbox Code Playgroud)
但是,我想在引用链接的文本中找到包含“Fetch”一词的链接。
我试过表格
soup.findAll('a', re.compile(".*Fetch.*"))
Run Code Online (Sandbox Code Playgroud)
但这行不通。如何仅选择具有 href 且文本部分中包含“Fetch”一词的标签 a?
正则表达式在这里可能有点矫枉过正,但它允许可能的扩展:
def criterion(tag):
return tag.has_attr('href') and re.search('Fetch', tag.text)
soup.findAll(criterion)
# [<a href="/downloadsServlet?docid=ixyz" target="_blank">Fetch Report 2 </a>]
Run Code Online (Sandbox Code Playgroud)
import re
soup.findAll('a', text = re.compile("Fetch"))
Run Code Online (Sandbox Code Playgroud)
您可以使用正则表达式作为过滤器,它将使用re.search方法来过滤我们的标签。
text/string是标签的文本值,text = re.compile("Fetch")表示查找文本值包含'Fetch'的标签
还有一件事,使用find_all()或者findAll(),findall()是不是在BS4的关键词