baohanblog

爬取汽车之家新闻

# 爬取汽车之家

import requests

# 向汽车之家发送get请求,获取到页面
ret = requests.get(\'https://www.autohome.com.cn/news/1/#liststart\')
# print(ret.text)

# bs4解析(可以不用re)
from bs4 import BeautifulSoup
# 实例化得到对象,传入要解析的文本和解析器
# html.parser是一个内置解析器,速度稍微慢一些,但是不需要装第三方模块
# lxml:速度快一些,但是需要安装 pip3 install lxml
soup = BeautifulSoup(ret.text,\'html.parser\')
# soup=BeautifulSaoup(open(\'a.html\',\'r\'))
# find(找到的第一个)
# find_all(找所有的)
# 找页面所有的li标签
li_list = soup.find_all(name=\'li\')
for li in li_list:
    # li是Tag对象
    # print(type(li))
    h3 = li.find(name=\'h3\')
    if not h3:
        continue
    title = h3.text
    desc = li.find(name=\'p\').text
    # 对象支持[]取值,说明重写了__getitem__魔法方法
    img = li.find(name=\'img\')[\'src\']
    url = li.find(name=\'a\')[\'href\']
    # 图片下载到本地
    ret_img = requests.get(\'https:\'+ img)
    img_name = img.rsplit(\'/\',1)[-1]
    with open(img_name,\'wb\')as f:
        for line in ret_img.iter_content():
            f.write(line)
    print(\'\'\'
    新闻标题:%s
    新闻摘要:%s
    新闻链接:%s
    新闻图片:%s
    \'\'\'%(title,desc,url,img))

 

分类:

技术点:

相关文章: