【问题标题】:BeautifulSoup find all occurrences of specific textBeautifulSoup 查找所有出现的特定文本
【发布时间】:2015-10-16 17:30:15
【问题描述】:

我将分析许多具有不同 html 的网站,并尝试使用 BeautifulSoup 查找包含特定文本(在 html 内)的所有行。

r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")               
for text in soup.find_all():
    if "price" in text:
        print text

这种方法不起作用(即使“价格”在 html 中被提及超过 40 倍)。也许有更好的方法来做到这一点?

【问题讨论】:

  • 您是否有理由要使用BeautifulSoup?似乎如果您只想要包含价格的行,那么直接查看响应数据可能会更容易。最终目标是什么?

标签: python html parsing beautifulsoup


【解决方案1】:

为什么不让BeautifulSoup 找到包含所需文本的节点:

for node in soup.find_all(text=lambda x: x and "price" in x):
    print(node)

【讨论】:

  • 喜欢这个想法,但上面的代码不起作用,我改变了打印(py 2.7)我忘记了其他什么:)?欢呼
【解决方案2】:

在 bs4 4.7.1 中,您可以使用带有 * 的 :contains 伪类来考虑所有元素。显然,一些重复,因为父母可能包含具有相同文本的孩子。这里我搜索price

import requests
from bs4 import BeautifulSoup

url = 'https://www.visitsealife.com/brighton/tickets/'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'lxml')
items = soup.select('*:contains(price)')
print(items)
print(len(items))

【讨论】:

    【解决方案3】:

    要从给定的 URL 中提取所有文本,您可以使用以下内容:

    r = requests.get(url)
    soup = BeautifulSoup(r.content, "lxml")               
    
    for element in soup.findAll(['script', 'style']):
        element.extract()
    
    text = soup.get_text()
    

    这还将删除scriptstyle 部分中可能不需要的文本。然后,您可以使用它搜索所需的文本。

    【讨论】:

      【解决方案4】:

      您不必使用 Beautiful soup 来查找 html 中的特定文本,而是可以使用该请求例如:

      r = requests.get(url)
      if 'specific text' in r.content:
          print r.content
      

      【讨论】:

        猜你喜欢
        • 2012-10-25
        • 1970-01-01
        • 1970-01-01
        • 2019-10-05
        • 2018-10-11
        • 2015-09-05
        • 2014-05-09
        • 1970-01-01
        • 2016-09-07
        相关资源
        最近更新 更多