python - 使用 Python 的 BeautifulSoup 提取包含特定子字符串的 'a' 标签

标签 python web-scraping tags beautifulsoup recompile

使用 BeautifulSoup,我只想在其 href 字符串中返回包含“Company”而不是“Sector”的“a”标签。有没有办法在 re.compile() 中使用正则表达式来仅返回公司而不返回部门?

代码:

soup = soup.findAll('tr')[5].findAll('a') print(soup)

输出

[<a class="example" href="../ref/index.htm">Example</a>,  
<a href="?Company=FB">Facebook</a>,  
<a href="?Company=XOM">Exxon</a>,  
<a href="?Sector=5">Technology</a>,  
<a href="?Sector=3">Oil & Gas</a>]  

使用这个方法:

import re soup.findAll('a', re.compile("Company"))

返回:

AttributeError: 'ResultSet' object has no attribute 'findAll'

但我希望它返回(没有扇区):

[<a href="?Company=FB">Facebook</a>,<br/> <a href="?Company=XOM">Exxon</a>]

使用:

  • urllib.request 版本:3.5
  • BeautifulSoup 版本:4.4.1
  • Pandas 版本:0.17.1
  • python 3

最佳答案

使用 soup = soup.findAll('tr')[5].findAll('a') 然后 soup.findAll('a', re.compile("Company ")) 覆盖原来的 soup 变量。 findAll 返回一个 ResultSet,它基本上是一组 BeautifulSoup 对象。尝试使用以下方法获取所有“公司”链接。

links = soup.findAll('tr')[5].findAll('a', href=re.compile("Company"))

获取这些标签中包含的文本:

companies = [link.text for link in links]

关于python - 使用 Python 的 BeautifulSoup 提取包含特定子字符串的 'a' 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37059421/

相关文章:

Facebook Graph 2.2 - 忽略批量请求中的错误

web-scraping - 制表符分隔的 csv 而不是在 scrapy 中分隔的逗号

python beautifulsoup 将属性添加到没有值的标签

windows - 如何防止Safari自动播放HTML5音频元素

jquery - 预填充标签管理器

php - 如何检测图像是 PNG 还是 APNG 格式?

python - 合并重复的列 Pandas

python - 登录销售导航器 python selenium

python - 用于模糊字符串比较的好 Python 模块?

python - 使用 Adwords API 将自定义受众群体添加到广告组