环境:
MacOS High Sierra
Python3.5+Anaconda
问题:
采集自己豆瓣上的信息。
产生原因:
用 urllib.request.urlopen 方式打开一个URL,服务器端会收到对于该页面的访问请求。由于服务器缺失信息,包括浏览器,操作系统,硬件平台等,将视为一种非正常的访问。
有些网站为防止这种非正常的访问会验证请求信息中的UserAgent。在代码中加入UserAgent信息即可。
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
req = urllib.request.Request(url=chaper_url, headers=headers)
context = urllib.request.urlopen(req).read() 如何获取Header?
在chrome浏览器中点击“检查”,选择network-》name列表下随便点一个-》header
如下图所示。
*问题:我用自己浏览器里得来的Header仍然报错,但是用了上文代码中的header作为代理浏览器即可使用。
**问题更新:豆瓣提供API,因此为了保护用户隐私,可能对于爬虫有更严格的限制。我用自己的爬虫可以爬自己的音乐记录,但是不能爬读书记录。所以打算申请一个豆瓣的API KEY。
code原文贴在下面
"""
Created by LiXuefei in 2017.07.26
"""
import urllib.request
from urllib.request import urlopen
import pandas as pd
# beautifulsoup方法,第三方库的方法,爬找网页
## 下载网页
from bs4 import BeautifulSoup
def get_content(url):
headers = {'User-Agent': 'mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/27.0.1453.94 safari/537.36'}
#Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
req = urllib.request.Request(url=url, headers=headers)
content = urllib.request.urlopen(req).read().decode('utf-8')
return content
def get_txt(info):
info_name = []
info_time = []
soup = BeautifulSoup(info,"lxml") # 设置解析器为“lxml”
#print(soup)
name = soup.select(".item > .info ul li a em") # .intro"#.product-image-and-name-container > .product-image')#.product-name product-image
information = soup.select(".item > .info ul > .intro")#空格的问题
time = soup.select(".item > .info ul li > .date ")
for names in name:
temp_name = str(names).strip('<em>' + '</em>' + '\n' + '\'')
info_name.append(temp_name)
#dataset['name'].append(temp_name)
for x in range(len(time)):
time[x] = str(time[x]).strip('<span class="date">' + '</span>' + '\n' + '\'')
info_time.append(time[x])
return info_name,info_time
info = []
time = []
for k in range(25):
start = str(15*k)
temp_url = "https://movie.douban.com/people/62209085/collect?start=" + start + "&sort=time&rating=all&filter=all&mode=grid" #"
content = get_content(temp_url)
mov_name,mov_time = get_txt(content)
x = 0
for x in range(len(mov_name)):
info.append(mov_name[x])
time.append(mov_time[x])
print("success")
print(len(info),len(time))
dataset = pd.DataFrame()
dataset['info'] = info
dataset['time'] = time
#
dataset.to_csv('/Users/lixuefei/Desktop/movie.csv')
#
# print(dataset)
参照自:http://blog.csdn.net/eric_sunah/article/details/11301873
版权声明:本文为leeafay原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。