【问题标题】:How to fetch the specific data from website using regular expression?如何使用正则表达式从网站获取特定数据?
【发布时间】:2021-12-30 08:59:20
【问题描述】:

我是 python web 抓取的新手。我正在尝试构建一个仅从网站获取粗体文本下方的普通文本的脚本 - https://www.state.gov/cuba-restricted-list/list-of-restricted-entities-and-subentities-associated-with-cuba-effective-january-8-2021/

即只喜欢文本 MINFAR — Ministerio de las Fuerzas Armadas Revolucionarias 和 MININT — Ministrys 下的Ministerio del Interior 类似地直到Additional Subentities of Habaguanexand 并将它们存储为列表。我尝试使用以下代码获取那些。但我无法单独获取那些正常的文本值。

这是我的代码:

import requests

import re

from bs4 import BeautifulSoup


URL = "https://www.state.gov/cuba-restricted-list/list-of-restricted-entities-and-subentities-associated-with-cuba-effective-january-8-2021/"
page = requests.get(URL)

soup = BeautifulSoup(page.text, "lxml")

content = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['entry-content'])

print(content)

欢迎任何想法的朋友。请随时分享您的想法。提前谢谢你:)

【问题讨论】:

    标签: python html web-scraping beautifulsoup python-requests


    【解决方案1】:

    我查看了网站的 HTML 代码,看看它有什么样的格式。似乎所有项目都包含在一个带有 entry-content 类的 div 中,就像您自己发现的那样。
    然后我也发现所有的文字都被<p>标签包裹了,但是我们要排除的标题也被这个p标签内的<b>标签包裹了。这意味着我们可以过滤掉任何以<b> 标记开始的标记。重要的是我们只过滤掉以<b> 开头的标签,因为有一些像<p>Gran Hotel Bristol Kempinski <b><i>Effective</i></b><b><i>November 15</i></b><b><i>, 2019</i></b></p> 这样的有效条目是列表中的条目,但在包装<p> 标签的后面只有粗体标签。

    在脚本中,我使用p.encode_contents() 将HTML 作为字符串来查看它是否以<b> 标记开头。请注意,此函数返回一个字节串,因此必须使用 b"" 与另一个字节串进行比较。
    还有一点是它跳过了前两个标签,因为它们属于页面的描述。

    import requests
    from bs4 import BeautifulSoup
    
    URL = "https://www.state.gov/cuba-restricted-list/list-of-restricted-entities-and-subentities-associated-with-cuba-effective-january-8-2021/"
    page = requests.get(URL)
    
    soup = BeautifulSoup(page.text, "lxml")
    
    content = soup.find_all("div", {"class": "entry-content"})[0]
    
    results = []
    for p in content.find_all('p')[2:]:
        if not p.encode_contents()[:3] == b"<b>" and p.text:
            results.append(p.text)
    
    print(results)
    

    此代码遍历.entry-content 标记中的所有&lt;p&gt; 标记,并检查它是否以&lt;b&gt; 标记开头。然后只保存那些没有的文本。最后它只打印包含所有名称的数组。

    【讨论】:

    • 非常感谢兄弟!感谢您宝贵的时间来分享这些知识。您对每一步的解释都非常好,它确实非常有助于学习寻找解决方案的新方法。谢谢!再次兄弟。祝你有美好的一天:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多