【问题标题】:BeautifulSoup.find_all(), can I select multiple tags and strings within those tags?BeautifulSoup.find_all(),我可以在这些标签中选择多个标签和字符串吗?
【发布时间】:2021-11-08 05:32:03
【问题描述】:

我希望从网站上抓取一些数据。作为序言,我是新手。我希望根据邮政编码专门过滤所有返回的 XML 数据(邮政编码在 'item_teaser' 下)。

<item lat="43.6437075296758" long="-80.083111524582" item_name="Acton Golf Club" item_url="http://www.ontariogolf.com/courses/acton/acton-gc/" item_teaser="4955 Dublin Line Acton, Ontario L7J 2M2"/>

以上是我尝试提取的示例,但我想通过特定邮政区域过滤所有内容(前 3 个字母,例如 L7J)

find_all()可以通过item_teaser找到“L7J、L2S、L2O等”相关的字符串吗?并返回那些匹配的邮政区域,包括整个项目? 下面的代码是错误的,因为我无法提取任何东西,但这是我目前所拥有的。

from bs4 import BeautifulSoup

url = "http://www.ontariogolf.com/app/map/cfeed.php?e=-63&w=-106&n=55&s=36"
xml = requests.get(url)
# I was just seeing if I could grab everything from the website which worked when I printed.
soup = BeautifulSoup(xml.content, 'lxml')
# I am trying to show all item teasers just to try it out, but I can't seem to figure it out
tag = soup.find_all(id="item_teaser")
print(tag)

【问题讨论】:

    标签: python beautifulsoup findall


    【解决方案1】:

    您可以检查多个字符串 [matches list] 是否存在于另一个字符串 [attribute with name = "item_teaser"]

    from bs4 import BeautifulSoup
    import requests
    
    url = "http://www.ontariogolf.com/app/map/cfeed.php?e=-63&w=-106&n=55&s=36"
    xml = requests.get(url)
    soup = BeautifulSoup(xml.content, 'lxml')
    input_tag = soup.find_all('item')
    
    # put the list of associated strings here
    matches = ["L7J", "L1S", "L2A"]
    
    # print the result
    for tag in input_tag:
        text= tag["item_teaser"]    
        if any(x in text for x in matches):
            print(text)
    

    【讨论】:

    • 这肯定更符合我正在尝试做的事情。在“如果有的话……”声明中。 “x”是一个任意变量,只是试图查看文本中的匹配项和匹配项吗?我正在尝试这段代码,它看起来像我想要的,但它仍然返回整个省,而不是匹配“匹配”和“文本”的特定高尔夫球场。如果匹配和文本中没有邮政编码(例如 L2S),这会影响迭代的工作方式吗? Try except 能解决这个问题吗?
    【解决方案2】:

    当你在做的时候:

    tag = soup.find_all(id="item_teaser")
    

    BeautifulSoup 正在寻找名为“item_teaser”的 HTML ID。然而,“item_teaser”不是一个id,它是一个属性

    要搜索所有item-teaser,您可以将该标签作为关键字参数传递给BeautifulSoup

    for tag in soup.find_all(item_teaser=True):
        print(tag)
    

    另外,要访问item-teaser属性,可以使用tag[<attribute>]

    for tag in soup.find_all(item_teaser=True):
        print(tag["item_teaser"])
    

    【讨论】:

    • 谢谢!!这解决了我至少检索“item_teaser”的问题!!我是否能够以某种方式使用它来过滤所有项目以仅返回 item_teaser 中具有与特定字符串匹配的属性的项目(例如邮政编码的前 3 个字母)?
    • @SenadH 要按文本查找标签,请考虑查看thisthis
    • 这看起来是我想要做的!我去四处看看,搞清楚!我非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多