【问题标题】:Skipp the error while scraping a list of urls form a csv从 csv 中抓取 url 列表时跳过错误
【发布时间】:2018-10-24 00:00:53
【问题描述】:

我设法从 CSV 文件中抓取了一个 url 列表,但我遇到了一个问题,抓取在遇到断开的链接时会停止。它还打印了很多 None 行,是否可以摆脱它们?

在此不胜感激。先感谢您 !

代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup #required to parse html
import requests #required to make request

#read file
with open('urls.csv','r') as f:
    csv_raw_cont=f.read()

#split by line
split_csv=csv_raw_cont.split('\n')

#specify separator
separator=";"

#iterate over each line
for each in split_csv:

    #specify the row index
    url_row_index=0 #in our csv example file the url is the first row so we set 0

    #get the url
    url = each.split(separator)[url_row_index] 

    #fetch content from server
    html = requests.get(url).content

    #soup fetched content
    soup = BeautifulSoup(html,'lxml')

    tags = soup.find("div", {"class": "productsPicture"}).findAll("a")

    for tag in tags:
       print(tag.get('href'))

出现错误的结果如下所示:

https://www.tennis-point.com/asics-gel-resolution-7-all-court-shoe-men-white-silver-02013802720000.html
None
https://www.tennis-point.com/cep-ultralight-run-sports-socks-men-black-light-green-12143000063000.html
None
https://www.tennis-point.com/asics-gel-solution-speed-3-clay-court-shoe-men-white-grey-02013802634000.html
None
https://www.tennis-point.com/asics-gel-solution-speed-3-all-court-shoe-men-white-silver-02013802723000.html
None
https://www.tennis-point.com/asics-gel-challenger-9-indoor-carpet-shoe-men-white-grey-02012401735000.html
None
https://www.tennis-point.com/asics-gel-court-speed-clay-court-shoe-men-dark-blue-yellow-02014202833000.html
None
https://www.tennis-point.com/asics-gel-court-speed-all-court-shoe-men-white-silver-02014202832000.html
None
Traceback (most recent call last):
File "/Users/imaging-adrian/Desktop/Python Scripts/close_to_work.py", line 33, in <module>
tags = soup.find("div", {"class": "productsPicture"}).findAll("a")
AttributeError: 'NoneType' object has no attribute 'findAll'
[Finished in 3.7s with exit code 1]
[shell_cmd: python -u "/Users/imaging-adrian/Desktop/Python 
Scripts/close_to_work.py"]
[dir: /Users/imaging-adrian/Desktop/Python Scripts]
[path: /Users/imaging-adrian/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/munki]

我的 CSV 文件中的链接如下所示:

https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E701Y-0193;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E601N-4907;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E601N-0193;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E600N-0193;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E326Y-0174;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E801N-4589;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E800N-0193;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E800N-9093;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E800N-4589;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E804N-9095;

【问题讨论】:

  • 你能修正你的缩进吗?此外,请始终尝试使用 csv 模块来解析 csv 文件。不要用split 解析它。
  • :( 抱歉,我对 Python 很陌生。
  • @AnotherUser31 即使你是 Python 新手,你肯定知道 Python 使用缩进来分隔代码块,所以你的代码 sn-p 不仅无效,其他开发者也无法理解控制流。
  • @brunodesthuilliers 我明白了!我会努力解决的!给我一分钟

标签: python csv screen-scraping


【解决方案1】:

这是工作版本,

from bs4 import BeautifulSoup
import requests
import csv

with open('urls.csv', 'r') as csvFile, open('results.csv', 'w', newline='') as results:
    reader = csv.reader(csvFile, delimiter=';')
    writer = csv.writer(results)

    for row in reader:
        # get the url
        url = row[0]

        # fetch content from server
        html = requests.get(url).content

        # soup fetched content
        soup = BeautifulSoup(html, 'html.parser')

        divTag = soup.find("div", {"class": "productsPicture"})

        if divTag:
            tags = divTag.findAll("a")
        else:
            continue

        for tag in tags:
            res = tag.get('href')
            if res != None:
                writer.writerow([res])

【讨论】:

  • 我认为你已经接近了,我刚刚收到一条错误消息:SyntaxError: 'continue' not proper in loop
  • 第一部分是正确的(continue 语句可能除外),第二部分是 WTF - tags 将是一个空列表或 tag.a 对象列表 - 它会永远不要同时包含标签和None 值。
  • 好吧,设法修复了继续。它应该在分号内“继续”。但是我得到了另一个错误,NameError: name 'findAll' is not defined :(
  • @AnotherUser31 应该是divTag.findAll("a")(我在答案中修复了它)。
  • @brunodesthuilliers 没有错误,但也没有链接 :( 它应该打印一些 url :((
猜你喜欢
  • 2020-02-16
  • 2018-07-01
  • 2020-09-02
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 2020-06-17
相关资源
最近更新 更多