【问题标题】:Why Is Beautiful Soup Only Giving Me the First Entry in a Website?为什么 Beautiful Soup 只给我一个网站的第一个条目?
【发布时间】:2019-09-21 12:49:46
【问题描述】:

我正在尝试从以下网站上列出的文章中获取标题、日期和作者:https://coreyms.com/

这是我运行的代码

from bs4 import BeautifulSoup
import requests
import lxml
import csv
source = requests.get('http://coreyms.com').text
soup=BeautifulSoup(source,'lxml')

for match in soup.find_all('div',class_='site- 
container'):

    headline=match.main.header.h2.a.text
    print(headline)
    date=match.main.header.p.time.text
    print(date)
    author=match.main.header.p.span.a.span.text
    print(author)

    print()

但是,当我运行此代码时,我仅从第一项中获取信息。任何帮助将非常感激。谢谢!

【问题讨论】:

    标签: web-scraping beautifulsoup lxml


    【解决方案1】:

    试试这个方法:

    match = soup.find_all('h2')
    for i in match:
        print(i.text)
        print(i.nextSibling.nextSibling.find('time').text)
        print(i.nextSibling.nextSibling.find('span').text)
        print('====')
    

    输出:

    Python Threading Tutorial: Run Code Concurrently Using the Threading Module
    September 12, 2019
    Corey Schafer
    ====
    Update (2019-09-03)
    September 3, 2019
    Corey Schafer
    ====
    

    等等

    【讨论】:

    • 谢谢。这行得通。问:你为什么写下一个兄弟姐妹?我在源代码中没有看到。
    • @Andrew - 目标数据项彼此相邻设置(就像兄弟/姐妹一样),但有两步之遥(不相关的项目卡在中间)。要从title 到达dateauthor,您需要横向走两步(这就是为什么使用两次BS 方法nextSibling()。顺便说一句,不要忘记也接受答案。
    【解决方案2】:

    我会采用一种更快的方法,即选择所有文章标签,然后在循环中使用类选择器来获取您想要的信息

    import requests
    from bs4 import BeautifulSoup as bs
    
    r = requests.get('https://coreyms.com/')
    soup = bs(r.content, 'lxml')
    
    for article in soup.select('article'):
        title = article.select_one('.entry-title-link').text
        date = article.select_one('.entry-time').text
        author = article.select_one('.entry-author-name').text
        print(title, date, author)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-31
      • 2014-05-02
      • 2021-01-30
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 2020-12-16
      相关资源
      最近更新 更多