【问题标题】:Python BeautifulSoup - scraping multiple pages and export result to CVSPython BeautifulSoup - 抓取多个页面并将结果导出到 CVS
【发布时间】:2021-11-29 05:32:45
【问题描述】:

我想在不同的页面中抓取一些信息。下面的代码可以帮助我用 print() 函数抓取信息。

问题是我只从最后一页获取数据。上一页的结果无法写入 CSV 文件。我该怎么办?谢谢。

代码:

enter code here
import requests
from csv import writer
from bs4 import BeautifulSoup

urls = ['https://www.xxxxxxxxxxxxxxx/02-nb.php','https://www.xxxxxxxxxxxxxxx/03-np.php','https://www.xxxxxxxxxxxxxxx/04-nb.php']

for index,url in enumerate(urls):
    requests.get(url)
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'lxml')
    print(soup)
    table_data = soup.find('table')

with open("words.csv", "wt",newline='',encoding='utf-8') as csv_file:
    csv_data = writer(csv_file, delimiter =',')
    for voc in table_data.find_all('tr'):
        row_data = voc.find_all('td')
        row = [tr.text for tr in row_data]
        csv_data.writerow(row)

【问题讨论】:

    标签: python csv web-scraping beautifulsoup


    【解决方案1】:

    您正在遍历每个 URL,但您编写的将数据写入 CSV 的逻辑不在 for 循环之外,因此它只是将最后一点数据写入文件。我相信你想要的是:

    for index,url in enumerate(urls):
        requests.get(url)
        page = requests.get(url)
        soup = BeautifulSoup(page.text, 'lxml')
        print(soup)
        table_data = soup.find('table')
        
        if index:
            mode = "a"
        else:
            mode = "w"
    
        with open("words.csv", mode, newline='',encoding='utf-8') as csv_file:
            csv_data = writer(csv_file, delimiter =',')
            for voc in table_data.find_all('tr'):
                row_data = voc.find_all('td')
                row = [tr.text for tr in row_data]
                csv_data.writerow(row)
    

    这将在每次迭代中通过urls 写入words.csv,而不是遍历所有urls 并在最后一次迭代中写入words.csv

    【讨论】:

    • 为什么要区别对待第一个块?
    • 这是以“追加”(“a”)模式或“写入”模式打开文件的区别——“写入”会覆盖文件的现有内容,但追加不会。
    • 如果您只需要清除预先存在的文件,那么像open(filename, 'w').close() 那样打开和关闭它是有意义的,从而消除了代码重复
    • 感谢您的帮助
    【解决方案2】:
    with open("words.csv", "a",newline='',encoding='utf-8') as csv_file:
        csv_data = writer(csv_file, delimiter =',')
        for voc in table_data.find_all('tr'):
            row_data = voc.find_all('td')
            row = [tr.text for tr in row_data]
            csv_data.writerow(row)
    

    这段代码应该向右缩进以便在每次迭代中执行。另请注意,打开模式应该是“a”,它代表“w”模式下的“追加”,您每次都会覆盖文件

    【讨论】:

    • 感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多