《python3爬虫、数据清洗与可视化实战》第二章 简单的爬虫

2019-07-14  本文已影响0人  LZzzHe

2.1 关于爬虫的合法性

# 除前面指定的爬虫外,不允许其他爬虫爬取任何数据。
User-Agent: *
Disallow: /

2.2 认识网页结构

2.3 使用GET方式抓取数据

import requests #导入requests包
url = 'http://www.cntour.cn/' 
strhtml = requests.get(url) #GET方式,获取网页数据
print(strhtml.text) #表示网页源代码

2.4 使用POST抓取数据

import requests
import json
def get_translate_data (word=None):
  url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule '
  Form_data = {'i': word,
  'from': 'AUTO',
  'to': 'AUTO',
  'smartresult': 'dict',
  'client': 'fanyideskweb',
  'salt': '15629866146500',
  'sign': '3980757ebe914c2d22649888361da473',
  'ts': '1562986614650',
  'doctype': 'json',
  'version': '2.1',
  'keyfrom': 'fanyi.web',
  'action': 'FY_BY_REALTlME',
  'typoResult':'false'}
  response = requests.post(url,data = Form_data)
  content = json.loads(response.text)
  print(content['translateResult'][0][0]['tgt'])
if __name__ =='__main__':
  get_translate_data ('我爱数据')

2.5 使用 Beautiful Soup 解析网页

import requests
import pprint
from bs4 import BeautifulSoup
url = 'http://www.cntour.cn/'
strhtml = requests.get(url)
soup = BeautifulSoup(strhtml.text,'lxml') # 指定lxml解析器进行解析
data = soup.select('#main > div > div.mtop.firstMod.clearfix > div.leftBox > div:nth-child(2) > ul > li > a')
pprint.pprint(data)
#main > div > div.mtop.firstMod.clearfix > div.leftBox > div:nth-child(2) > ul > li > a

2.6 数据清洗

for item in data:
  result={
  'title':item.get_text(),
  'link':item.get('href')
  }
  print(result)
\d #匹配数字
+ #匹配前一个字符1次或多次
import re
for item in data:
  result = {
  'title':item.get_text(),
  'link':item.get('href'),
  'ID':re.findall('\d+',item.get('href'))
  }

2.6 爬虫攻防线

headers = {'User-Agent': 'Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36(KHTML, likeGecko) Chrome/70.0.3538.102 Safari/537.36'}
response = requests.post(url,data = Form_data,headers=headers)
import time
time.sleep(3)
proxies = {
"http":"http://10.10.1.10:3128",
"https":"http://10.10.1.10:1080",
}
response = requests.get(url,proxies=proxies)
上一篇 下一篇

猜你喜欢

热点阅读