418现象:网页对应的服务器做了身份验证,必须浏览器才能返回数据。如果不是浏览器发送的请求就会返回418
解决办法:设置请求的请求头中的用户信息为一个浏览器
import requests
headers = {
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
}
response = requests.get('https://movie.douban.com/top250', headers = headers)
if response.status_code == 200:
print(response.text)
bs4基本用法
1.创建网页对应的beautifulSoup对象
BeautifulSoup(网页数据,解析器名称)
网页数据——需要解析的网页源代码
解析器名称——lxml
from bs4 import BeautifulSoup
html = open('data.html', encoding='utf-8').read()
soup = BeautifulSoup(html, 'lxml')
2.获取标签
soup对象.select(css选择器)——在整个网页中获取css选择器选中的所有标签,返货值是列表,列表中的元素是标签对象
soup对象.select_one(css选择器)——在整个网页中获取css选择器选中的标签中的第一个标签,返回值撕标签对象
标签对象.elect(css选择器)——在指定标签中获取css选择器选中的所有标签,返货值是列表,列表中的元素是标签对象
标签对象.select(css选择器)——在指定标签中获取css选择器选中的标签中的第一个标签,返回值撕标签对象
soup.select() soup.select_one()
3.获取标签内容,获取标签属性
1)获取标签内容 标签对象.text
a = soup.select_one('div.c1>a')
print(a.text)
2)获取标签属性:标签对象.attrs[属性名]
print(a.attrs['href'])
练习:
如图文件data.html,内容如下:
Title
我是超链接0
我是span0
我是段落3
我是超链接2
-
泡面
3.5
元 -
火腿肠
2
元 -
矿泉水
1
元
-
数据分析
20000
23周 -
前端开发
22000
23周 -
java后端
23000
23周
练习1:获取所有课程的名字
from bs4 import BeautifulSoup
html = open('data.html', encoding='utf-8').read()
soup = BeautifulSoup(html, 'lxml')
p = soup.select('.course_list .name')
course_name = [x.text for x in p]
print(course_name)
练习2:获取第二个课程的价格
p = soup.select('.course_list .price')[1]
print(p.text)
p = soup.select_one('.course_list>li:nth-child(2)>.price')
print(p.text)
练习3:获取所有的课程以及对应的价格
# 方法一:
p = soup.select('.course_list p')
for i in p:
print(i.text)
# 方法二:
course_li = soup.select('.course_list li')
all_course = []
for li in course_li:
name = li.select_one('.name').text
price = li.select_one('.price').text
time = li.select_one('span').text
all_course.append({'name': name, 'price': price, 'time': time})
print(all_course)



