【问题标题】:BeautifulSoup 4: Extracting multiple titles and links from different ptag(s)BeautifulSoup 4:从不同的 ptag 中提取多个标题和链接
【发布时间】:2018-08-22 07:56:33
【问题描述】:

HTML 代码:

<div>
    <p class="title">
       <a href="/news/123456">title_1</a> 
    </p>
</div>

<div>
    <p class="title">
       <a href="/news/789000">title_2</a> 
    </p>
</div>

我的代码:

def web(WebUrl):
    site = urlparse(WebUrl)
    code = requests.get(WebUrl)
    plain = code.text
    s = BeautifulSoup(plain, "html.parser")
    p_containers = s.find('p', {'class':'title'})

    for title in s.find_all('p', {'class':'title'}):
        line = title.get_text()
        print(line)
        for link in p_containers.find_all('a'):
            line2 = link.get('href')
            print(site.netloc + str(line2))

大家好,我需要一些帮助,我的任务是从网页中提取标题和链接,我能够提取标题但不能提取链接。当我尝试抓取链接时,我只成功抓取了第一个链接,以下链接被忽略并替换为第一个抓取的链接。

【问题讨论】:

  • 不检查我认为答案可能是将p_containers = s.find('p', {'class':'title'}) 更改为p_containers = s.find_all('p', {'class':'title'})
  • 不,我错了,回答跟随!
  • Opps,for 循环中缺少缩进,它是嵌套的
  • 如果我的回答有帮助,您可以将其标记为已接受

标签: python web-scraping beautifulsoup web-crawler scrapy-spider


【解决方案1】:

您的代码中包含大部分位,但只有一点点。我认为获取标题和链接的最简单方法是使用以下内容。

site = """<div>
    <p class="title">
       <a href="/news/123456">title_1</a> 
    </p>
</div>

<div>
    <p class="title">
       <a href="/news/789000">title_2</a> 
    </p>
</div>"""

s = BeautifulSoup(site, "html.parser")

for title in s.find_all('p', {'class':'title'}):
    links = [x['href'] for x in title.find_all('a', href=True)]
    line = title.get_text()
    print(line)
    print(links)

您可以看到链接对象是一个列表,以防万一每个标题有多个链接的情况。

【讨论】:

    【解决方案2】:

    尝试这种方式将有助于从中找到_所有值。

    from bs4 import BeautifulSoup
    
    text = """<div>
        <p class="title">
           <a href="/news/123456">title_1</a> 
        </p>
    </div>
    
    <div>
        <p class="title">
           <a href="/news/789000">title_2</a> 
        </p>
    </div>
    """
    
    soup = BeautifulSoup(text, 'html.parser')
    for i in soup.find_all('p', attrs={'class': 'title'}):
        link = None
        if i.find('a'):
            link = i.find('a').get('href')
        print('Title:', i.get_text(strip=True), 'Link:', link)
    # Output as:
    # Title: title_1 Link: /news/123456
    # Title: title_2 Link: /news/789000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 2015-12-09
      • 2018-04-16
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      相关资源
      最近更新 更多