【发布时间】:2017-12-21 12:56:33
【问题描述】:
我制作了一个用于从网站上抓取一些数据的脚本,但它只运行了几页,之后它将停止并显示此消息“'NoneType' object has no attribute 'a'”。另一个错误是有时出现是这样的:
File "scrappy3.py", line 31, in <module>
f.writerow(doc_details)
File "C:\python\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u015f' in
position 251: character maps to <undefined>
你能给我一个建议如何解决这些错误吗?这是我的脚本:
import requests
import csv
from bs4 import BeautifulSoup
import re
import time
start_time = time.time()
page = 1
f = csv.writer(open("./doctors.csv", "w", newline=''))
while page <= 5153:
url = "http://www.sfatulmedicului.ro/medici/n_s0_c0_h_s0_e0_h0_pagina" + str(page)
data = requests.get(url)
print ('scraping page ' + str(page))
soup = BeautifulSoup(data.text,"html.parser")
for liste in soup.find_all('li',{'class':'clearfix'}):
doc_details = []
url_doc = liste.find('a').get('href')
for a in liste.find_all('a'):
if a.has_attr('name'):
doc_details.append(a['name'])
data2 = requests.get(url_doc)
soup = BeautifulSoup(data2.text,"html.parser")
a_tel = soup.find('div',{'class':'contact_doc add_comment'}).a
tel_tag=a_tel['onclick']
tel = tel_tag[tel_tag.find("$(this).html("):tel_tag.find(");")].lstrip("$(this).html(")
doc_details.append(tel)
f.writerow(doc_details)
page += 1
print("--- %s seconds ---" % (time.time() - start_time))
【问题讨论】:
-
你在哪一行得到这个?也许您可以使用堆栈跟踪发布整个错误消息。
-
soup.find('div',{'class':'contact_doc add_comment'})没有找到任何东西,返回None,所以.a失败。 -
@deceze 奇怪的是程序停在一个随机页面上,我已经在那个页面上检查过那个 div 是否存在。所以我想我需要实现一个重试的函数获取该 url 并再次解析它,直到找到 div。你能帮我解决我的第二个错误吗?
标签: python python-3.x web-scraping beautifulsoup