【问题标题】:Python3 web-scraper can't extract text from every <a> tag in the sitePython3 web-scraper 无法从站点中的每个 <a> 标记中提取文本
【发布时间】:2020-12-08 13:59:51
【问题描述】:

我正在尝试编写一个 Python3 网络抓取工具,用于从网站中提取 a 标记内的文本。

我正在使用带有此代码的 bs4 库:

from bs4 import BeautifulSoup
import requests

req = requests.get(mainUrl).text
soup = BeautifulSoup(req, 'html.parser')
for div in soup.find_all('div', 'turbolink_scroller'):
    for a in div.find_all('a', href=True, text=True):
       print(a.text)                                  

我遇到的唯一问题是它只能找到具有这种语法的文本:

<div class="test">
 <a href="/link/to/whatIwant">Text that i want</a>
</div>

但不是这个:

<div class="test">
  <a href="/link/to/whatIwant2">
    The text
    <br>
    I would like
  </a>
</div>

你能解释一下为什么吗?两者有什么区别?

【问题讨论】:

    标签: html python-3.x web-scraping beautifulsoup


    【解决方案1】:

    这可能与第二个div 中的&lt;br&gt; 标记有关。如果你删除text=True,你会得到它们。

    from bs4 import BeautifulSoup
    
    sample = """
    <div class="test">
     <a href="/link/to/whatIwant">Text that i want</a>
    </div>
    <div class="test">
      <a href="/link/to/whatIwant2">
        The text
        <br>
        I would like
      </a>
    </div>
    """
    
    for div in BeautifulSoup(sample, 'html.parser').find_all('div', 'test'):
        for a in div.find_all('a', href=True):
            print(a.getText(strip=True))
    

    输出:

    Text that i want
    The textI would like
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 2022-11-10
      相关资源
      最近更新 更多