【问题标题】:Scraping a list of urls using beautifulsoup and convert data to csv使用 beautifulsoup 抓取 url 列表并将数据转换为 csv
【发布时间】:2022-01-18 22:27:24
【问题描述】:

我是 Python 新手。以下问题:

  1. 我有一个要从中抓取数据的网址列表。我不知道我的代码有什么问题,我无法从所有 url 中检索结果。该代码仅抓取第一个 url 而不是其余的。如何成功抓取列表中所有 url 中的数据(标题、信息、描述、应用程序)?

  2. 如果问题 1 有效,如何将数据转换为 CSV 文件?

代码如下:

import requests
from bs4 import BeautifulSoup
from bs4 import BeautifulSoup
import lxml
import pandas as pd
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError

urlList = ["url1","url2","url3"...lists of urls.......]

for url in urlList:
    try:
        html = urlopen(url)
    except HTTPError as e:
        print(e)
    except URLError:
        print("error")
    else:
        soup = BeautifulSoup(html.read(),"html5lib")
# Scraping
def getTitle():
    for title in soup.find('h2', class_="xx").text:
            print(title)

def getInfo():
   for info in soup.find('ul', class_="j-k-i").text:
        print(info)

def getDescription():
    for description in soup.find('div', class_="b-d").text:
        print(description)

def getApplication():
    for application in soup.find('div', class_="g-b bm-b-30").text:
       print(application)

for soups in soup():
    getTitle()
    getInfo()
    getDescription()
    getApplication()

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    尝试以下方法:

    import requests
    from bs4 import BeautifulSoup
    from bs4 import BeautifulSoup
    import lxml
    import pandas as pd
    from urllib.request import urlopen
    from urllib.error import HTTPError
    from urllib.error import URLError
    import csv
    
    
    def getTitle(soup):
        return soup.find('h2', class_="xx").text
    
    def getInfo(soup):
        return soup.find('ul', class_="j-k-i").text
    
    def getDescription(soup):
        return soup.find('div', class_="b-d").text
    
    def getApplication(soup):
        return soup.find('div', class_="g-b bm-b-30").text
    
    urlList = ["url1","url2","url3"...lists of urls.......]
    
    with open('output.csv', 'w', newline='')  as f_output:
        csv_output = csv.writer(f_output)
        csv_output.writerow(['Title', 'Info', 'Desc', 'Application'])
        
        for url in urlList:
            try:
                html = urlopen(url)
            except HTTPError as e:
                print(e)
            except URLError:
                print("error")
            else:
                soup = BeautifulSoup(html.read(),"html5lib")
                row = [getTitle(soup), getInfo(soup), getDescription(soup), getApplication(soup)]
                print(row)
                csv_output.writerow(row)
                
    

    这会将当前的soup 传递给每个要使用的函数。现在每个函数都返回找到的文本(以前 for 循环一次打印一个字符)。

    最后,Python 的csv 库可用于轻松编写格式正确的 CSV 文件。它为每一行获取一个值列表,并默认在output.csv 中写入一个逗号分隔的行。

    注意:未测试,因为您没有提供任何合适的 URL。

    【讨论】:

    • 您好@martin,非常感谢您的回复。终端输出以单行形式出现。从链接中查看图片:i.postimg.cc/Kjt0vkQG/pythonoutput.png 有没有办法让我有一个终端输出,例如:1 [链接标题信息描述应用程序]
    • 有没有办法可以导出为 csv?
    • 您在字符串上使用 for 循环导致它一次打印一个字符。不需要循环。 Python 的 CSV 库可用于将值列表写入 CSV 文件中的一行。为此,您需要从每个函数中返回文本。
    • 怎么样,能不能帮我把脚本放进去?
    • 我已经更新答案了,刷新试试
    猜你喜欢
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多