爬虫爬取网页的信息与图片的方法
import requests
head = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
}
# 这是get请求带参数的模式
def get_param():
# 1、url
url = "https://www.sogou.com/web?"
# 2、发送请求 get带参数使用params参数
response = requests.get(url, headers=head, params={"query": "刘亦菲"})
# 3、获取想要的数据
with open("./dilireba.html", "w", encoding="utf8") as fp:
fp.write(response.text)
print(type(response.text))
pass
get_param()
import requests
def post_data():
# 1、url
url = 'https://fanyi.baidu.com/sug'
# 2、发送请求
response = requests.post(url, headers=head, data={"kw": "dog"})
# 获取想要的数据
print(response.json())
post_data()
import requests
from lxml import etree
if __name__ == '__main__':
tree = etree.parse("./test.html")#读取文件
# xpath返回的都是列表
# / 标识一个层级
print(tree.xpath("/html/body/div/p"))#找到想要数据的位置
print(tree.xpath("/html/head/title"))
# 定位百里守约 索引定位 从1开始
print(tree.xpath("/html/body/div[1]/p"))#读取第一个div的p
print(tree.xpath("/html/body/div/p[1]"))#读取body下面所有div下的第一个p
#
print(tree.xpath("/html/body/div[2]/a[2]"))
print(tree.xpath("/html/body/div[3]/ul/li[3]/a"))
#
# # // 标识多个层级 属性定位 attr = class id
# 定位李清照
print(tree.xpath("//div[@class='song']/p[1]"))
#查看class或id 对应的信息是不是独一无二的,如是采用div[@class='song']这种形式,如不是查看其上一级是不是独一无二的。
print(tree.xpath("//div[@class='song']/a[@class='du']"))
# # 取所有的li标签
print(tree.xpath("//div[@class='tang']/ul/li"))
# # 取li标签内的所有a标签
for li in tree.xpath("//div[@class='tang']/ul/li"):
try:#数据正确
print("".join(li.xpath("./a/text()")))#将列表形式变成字符串形式
except Exception as e:#数据失败,执行下一个,不会影响其他数据执行
pass
#
# # 取标签下的直系文本内容
print(tree.xpath("/html/body/div[1]/p/text()"))
# 取标签下的所有文本
print(tree.xpath("/html/body/div[2]//text()"))
# 取标签内的属性值 @attr_name
print(tree.xpath("//div[@class='song']/img/@src"))
test.html文件
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>测试bs4</title>
</head>
<body>
<div>
<p>百里守约</p>
</div>
<div class="song">
你好
<p>李清照</p>
<p>王安石</p>
<p>苏轼</p>
<p>柳宗元</p>
<a href="http://www.song.com/" title="赵匡胤" target="_self">
<span>this is span</span>
宋朝是最强大的王朝,不是军队的强大,而是经济很强大,国民都很有钱</a>
<a href="" class="du">总为浮云能蔽日,长安不见使人愁</a>
<img src="http://www.baidu.com/meinv.jpg" alt="" />
</div>
<div class="tang">
<ul>
清明时节雨纷纷,路上行人欲断魂
<li>
<a href="http://www.baidu.com" title="qing">
清明时节雨纷纷,路上行人欲断魂,借问酒家何处有,牧童遥指杏花村
</a>
</li>
<li>
<a href="http://www.163.com" title="qin">
秦时明月汉时关,万里长征人未还,但使龙城飞将在,不教胡马度阴山
</a>
</li>
<li><a href="http://www.126.com" alt="qi">岐王宅里寻常见,崔九堂前几度闻,正是江南好风景,落花时节又逢君</a></li>
<li><a href="http://www.sina.com" class="du">杜甫</a></li>
<li><a href="http://www.dudu.com" class="du">杜牧</a></li>
<li><b>杜小月</b></li>
<li><i>度蜜月</i></li>
<li><a href="http://www.haha.com" id="feng">凤凰台上凤凰游,凤去台空江自流,吴宫花草埋幽径,晋代衣冠成古丘</a></li>
</ul>
</div>
</body>
</html>
# pip install fake_useragent
import time
import requests
import fake_useragent
from lxml import etree
import re
if __name__ == '__main__':
# UA伪装
head = {
# "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
"User-Agent": fake_useragent.UserAgent().random
}
# 打开一个文件写入数据
fp = open("./doubanFilm.txt", "w", encoding="utf8")
# 1、url
# url = "https://movie.douban.com/top250"
# url2 = "https://movie.douban.com/top250?start=25&filter="
# url3 = "https://movie.douban.com/top250?start=50&filter="
for i in range(0, 250, 25):#所有网页地址
url = f"https://movie.douban.com/top250?start={i}&filter="
time.sleep(5)
# 2、发送请求
response = requests.get(url, headers=head)
# 3、获取想要的数据
res_text = response.text
# 4、数据解析
tree = etree.HTML(res_text)
# 定位所有的li标签
li_list = tree.xpath("//ol[@class='grid_view']/li") # 所有的li标签,包含信息
for li in li_list:
film_name = "".join(li.xpath(".//span[@class='title'][1]/text()")) # 改成字符串形式
director_actor_y_country_type = "".join(li.xpath(".//div[@class='bd']/p[1]/text()"))
score = "".join(li.xpath(".//span[@class='rating_num']/text()"))
quote = "".join(li.xpath(".//span[@class='inq']/text()"))
# director_actor_y_country_type需要修改
new_str = director_actor_y_country_type.strip() # 去除空格
y = re.match(r"([\s\S]+?)(\d+)(.*?)", new_str).group(2) # 正则表达式方式
country = new_str.rsplit("/")[-2].strip()
types = new_str.rsplit("/")[-1].strip()
director = re.match(r"导演: ([a-zA-Z\u4e00-\u9fa5·]+)(.*?)", new_str).group(1)
try:
actor = re.match(r"(.*?)主演: ([a-zA-Z\u4e00-\u9fa5·]+)(.*?)", new_str).group(2)
except Exception as e:
actor = "no"
fp.write(
film_name + "#" + y + "#" + country + "#" + types + "#" + director + "#" +
actor + "#" + score + "#" + quote + "\n") # 连接信息,连接符最好采用不常见的符号防止误读取
print(film_name, y, country, types, director, actor, score, quote)
fp.close()
import os.path
import fake_useragent
import requests
from lxml import etree
# UA伪装
head = {
"User-Agent": fake_useragent.UserAgent().random#自动伪装
}
pic_name = 0
def request_pic(url):
# 2、发送请求
response = requests.get(url, headers=head)
# 3、获取想要的数据
res_text = response.text
# 4、数据解析
tree = etree.HTML(res_text)
li_list = tree.xpath("//div[@class='slist']/ul/li")#获取所有的照片信息
for li in li_list:
# 1、获取照片的url
img_url = "https://pic.netbian.com" + "".join(li.xpath("./a/img/@src"))#img/@src,代表img的src属性
# 2、发送请求
img_response = requests.get(img_url, headers=head)
# 3、获取想要的数据
img_content = img_response.content
global pic_name
with open(f"./picLib/{pic_name}.jpg", "wb") as fp:#命名照片名称,并写下
fp.write(img_content)
pic_name += 1
if __name__ == '__main__':
if not os.path.exists("./picLib"):#若没有一个此文件夹,建立一个文件夹存放照片
os.mkdir("./picLib")
# 1、url
url = "https://pic.netbian.com/4kdongman/"
request_pic(url)
for i in range(2,10):#之后照片的url
next_url = f"https://pic.netbian.com/4kdongman/index_{i}.html"
request_pic(next_url)
pass
标签:xpath,网页,url,tree,爬虫,li,爬取,print,div
From: https://blog.csdn.net/mohanyelong/article/details/140588189