【问题标题】:Extract text from anchor tag in BeautifulSoup从 BeautifulSoup 中的锚标记中提取文本
【发布时间】:2018-12-29 05:17:27
【问题描述】:

我正在尝试从 URL 中提取标题,但它没有类。以下代码取自页面源代码。

<a href="/f/oDhilr3O">Unatama Don</a>

标题实际上确实有一个类,但您可以看到我使用了索引 3,因为前 3 个标题不是我想要的。但是,我不想使用硬编码。但在网站中,标题也是一个链接,因此,上面的链接。

title_name=soup.find_all('div',class_='food-description-title')
title_list=[]

for i in range (3,len(title_name)):
    title=title_name[i].text
    title_list.append(title)

"Unatama Don" 是我想要获得的标题。

【问题讨论】:

标签: python web-scraping beautifulsoup


【解决方案1】:

这是在 BS 中搜索具有特定 URL 的锚元素的示例:

from bs4 import BeautifulSoup

document = '''
  <a href="https://www.google.com">google</a>
  <a href="/f/oDhilr3O">Unatama Don</a>
  <a href="test">Don</a>
'''

soup = BeautifulSoup(document, "lxml")
url = "/f/oDhilr3O"

for x in soup.find_all("a", {"href" : url}):
    print(x.text)

输出:

Unatama Don

【讨论】:

    【解决方案2】:

    requests 和 bs4 模块对于这样的任务非常有帮助。您是否尝试过以下类似的方法?

    import requests
    from bs4 import BeautifulSoup
    
    url = ('PASTE/YOUR/URL/HERE')
    response = requests.get(url)
    page = response.text
    soup = BeautifulSoup(page, 'html.parser')
    links = soup.find_all('a', href=True)
    
    for each in links:
        print(each.text)
    

    我认为这具有您正在寻找的预期结果。如果您也想要超链接。添加另一个循环并在循环中添加“print(each.get('href'))”。让我们知道怎么回事。

    【讨论】:

      猜你喜欢
      • 2015-04-24
      • 1970-01-01
      • 2016-04-19
      • 2023-04-02
      • 2021-02-03
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 2016-01-29
      相关资源
      最近更新 更多