yafeng666

爬汽车之家新闻

"""
### 爬取汽车之家新闻


import requests

# 向汽车之家发送get请求,获取到页面

ret = requests.get(\'https://www.autohome.com.cn/news/1/#liststart\')
# print(ret.text)

# 用bs4解析
from bs4 import BeautifulSoup

# 实例化得到对象,传入要解析的文本,解析器
# html.parser内置解析器,速度要稍微慢一点,但是不需要装第三方模块
# lxml:速度快一些,得安装 pip install lxml

soup = BeautifulSoup(ret.text, \'html.parser\') # 传入一个字符串
# soup = BeautifulSoup(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))  # <class \'bs4.element.Tag\'>
    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\'] # type:str
    # print(img)
    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))
"""

分类:

技术点:

相关文章: