【问题标题】:Scraping urls from html, save in csv using BeautifulSoup从 html 中抓取 url,使用 BeautifulSoup 保存在 csv 中
【发布时间】:2014-05-18 00:59:42
【问题描述】:

我正在尝试将在线论坛中的所有超链接网址保存为 CSV 文件,以用于研究项目。

当我“打印”html 抓取结果时,它似乎工作正常,因为它打印了我想要的所有 url,但我无法将这些写入 CSV 中的单独行。

我显然做错了什么,但我不知道是什么!因此,我们将不胜感激任何帮助。

这是我写的代码:

import urllib2
from bs4 import BeautifulSoup
import csv
import re

soup = BeautifulSoup(urllib2.urlopen('http://forum.sex141.com/eforum/forumdisplay.php?    fid=28&page=5').read())

urls = []

for url in soup.find_all('a', href=re.compile('viewthread.php')):
        print url['href']

csvfile = open('Ss141.csv', 'wb')
writer = csv.writer(csvfile)

for url in zip(urls):
        writer.writerow([url])

csvfile.close()

【问题讨论】:

    标签: python-2.7 csv web-scraping beautifulsoup


    【解决方案1】:

    您确实需要将您的匹配项添加urls 列表中:

    for url in soup.find_all('a', href=re.compile('viewthread.php')):
        print url['href']
        urls.append(url)
    

    你不需要在这里使用zip()

    最好在找到它们时写下你的网址,而不是先将它们收集在一个列表中:

    soup = BeautifulSoup(urllib2.urlopen('http://forum.sex141.com/eforum/forumdisplay.php?fid=28&page=5').read())
    
    with open('Ss141.csv', 'wb') as csvfile:
        writer = csv.writer(csvfile)
        for url in soup.find_all('a', href=re.compile('viewthread.php')):
            writer.writerow([url['href']])
    

    with 语句将在块完成后为您关闭文件对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 2016-10-28
      • 2020-09-02
      • 2018-02-02
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多