怎么用python抓取网页数据
抓取网页需要导入模块: from bs4 import BeautifulSoup获取网页元素 import pandas 数据插入execl表 如何结合数据库需要导入pymysql模块 使用游标execute sql语句查询fetchall获取结果集 通过for变量将结果集转化成列表 #a=pandas.DataFrame(d)//建议使用列表数据类型 #a.to_excel(’./b.xlsx’)//将列表数据写入exec表 import urllib下载文件核心模块 下载照片 urllib.request.urlretrieve(url网站资源链接位置,’./img/’+’%d’%x+’.jpg’本地) 下载小说 htmlq=requests.get(u,cookies=cookie,headers=header) textq=BeautifulSoup(htmlq.text,‘lxml’)//获取网页元素 hrefq=textq.find_all(“a”,class_=“nextchapter”)//find_all是非常灵活的 p=textq.find_all(“p”)//假设小说段落位于p标签里面 lis=[] for a in p: lis.append(a.string) file=open("./牧座.txt",“a”,encoding=‘utf-8’)//a模式需要先创建文件附加 for d in lis: file.write(d) ) w’写入模式(文件不存在时创建它) t’文本模式(默认,与其他模式结合使用) x’独占写模式,新建一个文件,如果该文件已存在则会报错。 a’附加模式(在既有文件末尾继续写入) b’二进制模式(与其他模式结合使用) +打开一个文件进行更新(可读可写,与其他模式结合使用) import re正则表达式结合使用
更新于2022年4月16号
```python
from bs4 import BeautifulSoup
import requests
import urllib
import re
# html_doc = "<html><head><title>The Dormouses story</title></head><body>"
# soup = BeautifulSoup4(html_doc, html.parser)
# print(soup.prettify())
# urllib.request.urlretrieve(
# "https://www.mi.com/index.html", ./img/{name}.jpg)
print("Hello, Python!") # 第二个注释
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
}
cookie = {
"deviceId": "xmdevice_c7h8wz1tpt47n3k8",
"xmuuid": "XMGUEST-0F161580-BD58-11EC-B4EF-5790B5C4FD79",
"XM_agreement": "0",
"smidV2": "20220416153725dab420372a50477234de8932e762c87b0036d150ad544d320",
"mstuid": "1650094645361_6104",
"xm_vistor": "1650094645361_6104_1650094645366-1650094645366",
"mstz": "| | 173239809.10 | | |",
"pageid": "81190ccc4d52f577",
"Hm_lvt_c3e3e8b3ea48955284516b186acf0f4e": "1650094645",
"Hm_lpvt_c3e3e8b3ea48955284516b186acf0f4e": "1650094645",
".thumbcache_2959214a7e70e5f2bd017e23a2a3e462": "VgEjMl2FLaLkBumRj2Wxns5TlV/r3VFeqb8viPeIigX6x9KnNrt88Ct+yXp+c57YRsTm+F2Y3GwezHR/0x7JYg % 3D % 3D",
"mishopDeviceId": "BVgEjMl2FLaLkBumRj2Wxns5TlV/r3VFeqb8viPeIigX6x9KnNrt88Ct+yXp+c57YRsTm+F2Y3GwezHR/0x7JYg",
}
# https://www.mi.com/index.html 是爬取对象的网站 cookie是浏览器的cookie需要改 headers 是头部 不需要改
htmlq = requests.get(网站地址,
cookies=cookie, headers=header)
textq = BeautifulSoup(htmlq.text, "lxml")
hrefq = textq.find_all("img", class_="thumb")
# img是img标签 class_="要下载图片的类名有可能有也有可能没有"
i = 0
for site in hrefq:
i = i+1
str = %s % (site)
# 正则取到链接src或者data-src 一般是取网站查找img图标看看图片的地址 通常http或者https 与 jpg png webp等等组合的才是图片
arr = re.findall(rdata-src="(.+?)", str)[0]
print(arr)
urllib.request.urlretrieve(
arr, ./img/%s.jpg % (i))
