python爬虫基础二:爬取网站方法及案列分析

爬取网站

import urllib.request
D=urllib.request.urlopen("https://www.baidu.com").read()	
print(D)

案列一、如何爬取豆瓣上出版社列表并写入文件中
python爬虫基础二:爬取网站方法及案列分析_第1张图片

 import urllib.request
    import re
    data=urllib .request.urlopen("https://read.douban.com/provider/all").read().decode("utf-8")
    pat='
(.*?)
' rst=re.compile(pat).findall(data) fh=open(“D:\\MyWork\\python.txt”,”w”) for i in range(0,len(rst)): print(rst[i]) fh.write(rst[i]) fh.close()

Urllib库
Urlretrieve(网址,本地文件存储地址) 直接下载网页到本地

import urllib.request
urllib.request.urlretrieve("https://www.baidu.com","./baidu.html")
urlcleanup #清除内存
Urlinfo()#查看相关网页的简介信息
file=urllib.request.urlopen("https://read.douban.com/provider/all")
file.info()
print(file.info())
getcode()#返回网页的状态码
Geturl()#返回当前访问的网页

超时设置

for i in range(0,100):
	file=urllib.request.urlopen("https://read.douban.com/provider/all",timeout=1)
    try:
       file = urllib.request.urlopen("https://read.douban.com/provider/all", timeout=1)
       print(len(file.read().decode("utf-8",'ignore')))
    except Exception as err:
        print("出现异常")

自动模拟HTTP请求(pose、get两种请求)
Get请求在网址之后加问号?字段=值and 字段=值
Get请求实战——实现百度信息自动搜索
案列一:

import urllib.request,re    
keyword="python"
keyword=urllib.request.quote(keyword)
for i in range(1,11):
     url="http://www.baidu.com/s?wd="+keyword+"&pn="+str(i-1)*10
    data=urllib.request.urlopen(url).read().decode("utf-8")
    pat="title:'(.*?)',"
    pat2='"title":"(.*?)",'
    rst1=re.findall(pat,data)
    rst2=re.compile(pat2).findall(data)
    for j in range(0,len(rst1)):
        print(rst1[j])
    for z in range(0, len(rst2)):
        print(rst2[z])

附加:大量爬网络数据时,被服务器运营人员封掉IP,阻断爬虫进行的措施。
IP 端口号 服务器地址 协议类型
180.107.179.44 8118 江苏苏州 HTTPS
要求:爬以上信息存储到excel中,excel创建名称为代理服务器.xlsx,
excel表头:IP 端口号 服务器地址 协议类型 连接状态
爬20条信息,连接状态写 可用或不可用

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from openpyxl import Workbook
from telnetlib import Telnet
wb = Workbook()
ws = wb.active
ws.append(['ip', '端口', '服务器地址', '协议类型', '是否可用'])
options = Options()
options.add_argument('--headless')
options.add_argument('--proxy-server=http://180.107.179.44:8118')
browser=webdriver.Chrome(options=options)
browser.get("https://www.xicidaili.com/wn/")
for i in range(2,22):
    ws.cell(row=i, column=1).value=browser.find_element_by_xpath('//*[@id="ip_list"]/tbody/tr['+str(i)+']/td[2]').text
    ws.cell(row=i,column=2).value=browser.find_element_by_xpath('//*[@id="ip_list"]/tbody/tr['+str(i)+']/td[3]').text
    ws.cell(row=i,column=3).value=browser.find_element_by_xpath('//*[@id="ip_list"]/tbody/tr['+str(i)+']/td[4]').text
    ws.cell(row=i,column=4).value=browser.find_element_by_xpath('//*[@id="ip_list"]/tbody/tr['+str(i)+']/td[6]').text
    try:
        Telnet(ws.cell(row=i, column=1).value,ws.cell(row=i,column=2).value,timeout=2)
        ws.cell(row=i, column=5).value="可用"
    except:
        ws.cell(row=i, column=5).value="不可用"

wb.save('./代理服务器.xlsx')

你可能感兴趣的:(Python)