Crawled pages generic code frame
import requests
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status() #若状态不是200,引发HTTPError异常
r.encoding=r.apparent_encoding
return r.text
except:
return "产生异常"
if __name__=="__main__":
url="http://www.baidu.com"
print(getHTMLText(url))
A: Jingdong commodity page crawling
import requests
url="https://pro.jd.com/mall/active/28bw6fLCSoxGTKKBiQZLmUrVoSKV/index.html"
try:
r=requests.get(url)
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.text[:1000])
except :
print("爬取失败")
r.status_code 200 is returned, directly crawl
Two: Amazon product page crawling
import requests
url="https://www.amazon.cn/dp/B07JMQTHWR/ref=s9_acsd_hps_bw_c2_x_0_i?pf_rd_m=A1U5RCOVU0NYF2&pf_rd_s=merchandised-search-2&pf_rd_r=PF3XEDEN44FP3A9EN2RM&pf_rd_t=101&pf_rd_p=3f149c06-7221-4924-a124-ebbe0310b38c&pf_rd_i=116169071"
try:
kv={'user-agent':'Mozilla/5.0'}
r=requests.get(url,headers=kv)
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.text[1000:2000])
except :
print("爬取失败")
r.status_code returned is 503, so it is necessary to modify headers fields to hide the identity of their own reptiles
Three: Baidu search keywords submitted
import requests
keyword="Python"
try:
kv={'wd':keyword}
r=requests.get("http://www.baidu.com/s",params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except :
print("爬取失败")
Suspected to be redirected
Four: 360 search keywords submitted
import requests
keyword="Python"
try:
kv={'q':keyword}
r=requests.get("http://www.so.com/s",params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except :
print("爬取失败")
success
Five: network picture of crawling and storage
Crawling successful, save the picture to the D drive, named abc.jpg
import requests
import os
url="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1585238676005&di=806d8fd3824fb2380f9c1f0d2d4ab76a&imgtype=0&src=http%3A%2F%2Fimg.article.pchome.net%2F00%2F38%2F35%2F30%2Fpic_lib%2Fwm%2FChuntian11.jpg"
path="D:/abc.jpg"
try:
if not os.path.exists(path): #判断图片是否存在
r=requests.get(url)
with open(path,'wb') as f:
f.write(r.content)
f.close()
print("文件保存成功")
else:
print("文件已存在")
except :
print("爬取失败")