selenium库的使用
先在命令行 pip install selenium安装好库
再下载geckodriver(火狐浏览器的driver,也可以使用Chrome,网上搜一下)
将下载的压缩包解压,把里面的geckodriver放到火狐浏览器的安装目录下,例如C:\Program Files\Mozilla Firefox
把火狐浏览器的安装目录添加到系统环境变量中的Path
爬虫代码
import re
from selenium import webdriver
import pandas as pd
import xlwt
import threading
import time
url = 'https://www.amazon.com/dp/' #亚马逊网址基础目录,后面跟产品号是各个产品对应的目录
df=pd.read_excel('srcdata.xlsx') #改成自己的原始数据路径,这里存储一列产品号——asin
savepath="info.xls" #改成自己的保存数据路径
nm =0 #设置读取srcdata文件的起始行
cancel = 100 # 设置结束读取srcdata的位置
CRAWL_EXIT = False
workbook = xlwt.Workbook(encoding = 'utf-8')
# 自定义线程
class crawlThread (threading.Thread):
def __init__(self, name, lock):
threading.Thread.__init__(self)
self.name = name
self.lock = lock
def run(self):
global nm
global CRAWL_EXIT
count_movie=0
out=self.name
worksheet = workbook.add_sheet(out)
#要爬取的网页关键内容
temp=('asin','电影名', '时长', '上映年份', '导演', '演员', '类别', '语言', '格式','版本','制片方','用户评分')
for i in range(12):
worksheet.write(0,i,temp[i])
while(CRAWL_EXIT != True):
#初始化电影名、时长、上映年份、导演、演员、类别、语言、格式、版本、制片方、用户评分
mtitle=""
runtime=""
release=""
director=""
actor=""
genre=""
language=""
mformat=""
version=""
producer=""
review=""
#使用火狐浏览器爬取①
browser = webdriver.Firefox()
#每爬完一个网页删除cookie减少被反爬概率
browser.delete_all_cookies()
if nm > cancel:
CRAWL_EXIT = True
self.lock.acquire() # 获得锁
#获得网址
try:
pro_id=str(df.loc[nm][