Web crawler study notes (2)-examples

Example one, directly crawl without modifying the head

import requests
url = "https://item.jd.com/47767508311.html"
try:
	r = 
	requests.get(url)
	r.raise_for_status()
	r.encoding = r.apparent_encoding
	print(r.text[:1000])
except:
	print("爬取失败")

Example two, some websites may detect the header 'User-Agent': 'python-requests / 2.11.1', and recognize that the current request to access is a crawler, so the header needs to be modified

import requests
url = "https://www.amazon.cn/dp/B07PJGB6DC?ref_=Oct_DLandingS_D_cc22c87e_61&smid=A26HDXW89ZT98L"
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])
except:
	print("爬取失败")

Example three: search engine keyword submission interface

Baidu's keyword interface: http://www.baidu.com/s?wd=keyword
360's keyword interface: http://www.so.com/s?q=keyword

Baidu

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("爬取失败")

360 search full code

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("爬取失败")

Example 4: Image crawling

import requests
import os
url = "https://bkimg.cdn.bcebos.com/pic/4a36acaf2edda3ccbd7b3d6406e93901203f92d3?x-bce-process=image/crop,x_0,y_0,w_1328,h_904/watermark,g_7,image_d2F0ZXIvYmFpa2UxODA=,xp_5,yp_5"
root = "/Users/mac/Downloads//"
path = root + url.split('/')[-1] + ".jpg" # + ".jpg" 使得保存下的文件以jpg格式存储
try:
	if not os.path.exists(root):
		os.mkdir(root)
	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("爬取失败")

url is the address of the picture, where is the root to be stored in the machine

Example 5: Full code for IP address query

import requests
url = "http://m.ip138.com/ip.asp?ip="
try:
	r = requests.get(url+'202.204.80.112')
	r.raise_for_status()
	r.encoding = r.apparent_encoding
	print(r.text[-500:])
except:
	print("爬取失败")

This did not come out, I do n’t know where the problem is ,,,,

Published 16 original articles · praised 0 · visits 456

Guess you like

Origin blog.csdn.net/weixin_43951831/article/details/104844926