文章目录
我从年后开始接触爬虫,学了一系列杂七杂八的课程,目前还在看崔老师的《Python3网络爬虫开发实战》,在此将个人总结分享出来,希望能够帮助到和我一样想要学习爬虫的朋友,也希望能够得到大神的指点!内容如下:
一、一般小型爬虫(单个文件)
1.查看网页类型,(动态还是静态)使用requests发送请求,建议使用会话
静态用bs,动态用json
2.是否需要登录,cookies,或传递参数,headers,或者使用代理
3.解析网页,查找元素,bs,json,或正则表达式,pyquery,lxml
推荐bs,json,正则
4.效率控制:单进程/多协程/多线程
5.数据存储txt,excel,二进制文件,csv或者数据库
import requests
from bs4 import BeautifulSoup
import re
import csv
import openpyxl
#设置请求头
headers = {
'cookie':'', #用于登录
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36', #模拟浏览器
}
#使用代理
proxies={
'http':'http://10.10.1.10:3128',
'https':'http://10.10.1.10:1080',
}
def get_page(url): #requests请求函数
s = requests.Session() #使用会话
response = s.get(url,headers=headers,proxies=proxies)
response.encoding='utf-8' #定义response对象的编码方式
if response.status_code == 200: #请求成功
return response
else:
print('请求失败!')
def parse_page(response): #BS解析函数
html = response.text
soup = BeautifulSoup(html,'html.parse')
items = soup.find_all('article',class_='product_pod')
for item in items:
h3 = item.find('h3')
a = h3.find('a')
print(a['title'])
p = item.find('p')
print(p['class'])
div = item.find('div',class_='product_price')
price = div.find('p',class_='price_color')
print(price.text)
save_file( )
def parse_page(html): #json解析
json_music = res_music.json()
# 使用json()方法,将response对象,转为列表/字典
list_music = json_music['data']['song']['list']
# 一层一层地取字典,获取歌单列表
for music in list_music:
# list_music是一个列表,music是它里面的元素
print(music['name'])
# 以name为键,查找歌曲名
print('所属专辑:'+music['album']['name'])
# 查找专辑名
print('播放时长:'+str(music['interval'])+'秒')
# 查找播放时长
print('播放链接:https://y.qq.com/n/yqq/song/'+music['mid']+'.html\n\n')
# 查找播放链接 """
save_file( )
def parse_page(response): #正则表达式解析
html = response.text
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'
+ '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'
+ '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',re.S)
items = re.findall(pattern,html)
for item in items:
dict_0 = {
'index':item[0],
'image':item[1],
'title':item[2],
'actor':item[3].strip()[3:],
'time':item[4].strip()[5:],
'score':item[5]+item[6]
}
save_file(dict_0)
def save_file(content): #文件保存
with open('test.txt','a+') as f: #txt保存
f.write(content)
with open('test.jpg','wb') as f: #二进制保存
f.write(content)
def save_file(content): #csv保存
csv_file = open('demo.csv','w+',newline='',encoding='utf-8') #可放置于头部,提高效率
#调用open()函数打开csv文件,传入参数:文件名“demo.csv”、写入模式“w+”、newline=''、encoding='utf-8'。
writer = csv.writer(csv_file) #可放置于头部,提高效率
# 用csv.writer()函数创建一个writer对象。
writer.writerow(['电影','豆瓣评分'])
#调用writer对象的writerow()方法,可以在csv文件里写入一行文字 “电影”和“豆瓣评分”。
writer.writerow(['银河护卫队','8.0'])
#在csv文件里写入一行文字 “银河护卫队”和“8.0”。
writer.writerow(['复仇者联盟','8.1'])
#在csv文件里写入一行文字 “复仇者联盟”和“8.1”。
csv_file.close() #可放于结尾,提高效率
#写入完成后,关闭文件就大功告成啦!
def save_file(content): #excel保存
wb=openpyxl.Workbook() #可放置于头部,提高效率
sheet=wb.active #可放置于头部,提高效率
sheet.title='new title' #可放置于头部,提高效率
sheet['A1'] = '漫威宇宙' #可放置于头部,提高效率
content = [['美国队长','钢铁侠','蜘蛛侠'],['是','漫威','宇宙', '经典','人物']]
for i in content:
sheet.append(i)
print(rows)
wb.save('Marvel.xlsx') #可放置于结尾,提高效率
def main(offset):
url = ' '+str(offset)+' '
response = get_page(url)
parse_page(response)
if __name__ == '__main__':
for i in range(n):
main(i)
二、难以破译的爬虫使用selenium
1.模拟打开浏览器
2.获取网页源码
3.进行模拟点击
4.网页解析存储数据
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import time
from urllib.parse import quote
#此行为命令行配置(设置缓存和禁用图片加载功能)
#SERVICE_ARGS = ['--load-images=false','--disk-cache=true']
#默认打开浏览器模式
#browser = webdriver.Chrome()
#以下为Chrome静默浏览器模式
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(chrome_options=chrome_options)
wait = WebDriverWait(browser,10)#指定等待时间10s
def get_page(url): #selenium默认解析
browser.get(url)
html = browser.page_source
soup=BeautifulSoup(html,'lxml')
input = browser.find_element_by_class_name('zu-top-add-question')
print(input.text) #获取文本
logo = browser.find_element_by_id('zh-top-link-logo')
print(logo.get_attribute('class')) #获取属性
def get_page(url): #使用BeautifulSoup解析
browser.get(url)
html = browser.page_source
soup=BeautifulSoup(html,'lxml')
contents = soup.find_all('div',class_='content')
for content in contents:
print(content.find('h1').text)
print(content.find('p').text.strip(''))
#以下省略相应代码