Python 实现网络爬虫小程序

一、引用相关模块

import requests
from bs4 import BeautifulSoup

二、配置 headers 和需要爬取的 url 地址

headers = {
    'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
}

url = 'https://www.autohome.com.cn/news/'

三、利用 requests 模块进行内容抓取,并通过 BeautifulSoup 获取抓取页面的内容 

response = requests.get(url,headers=headers)

''' # 设置解析字符集 
    response.encoding:获取解析内容的字符集
    response.apparent_encoding:响应字符集
'''
response.encoding = response.apparent_encoding 

soup = BeautifulSoup(response.text,features='html.parser')

html_node = soup.find(id='auto-channel-lazyload-article')

li_list = html_node.find_all('li')

for i in li_list:# 遍历 li 标签
    a = i.find('a')  # 获取每个li下的a标签  
    if a:
        print(a.attrs) # 获取a标签中的所有属性
        print(a.get('href')) # 获取a标签中的href属性
        print(a.find('h3')) 
获取到的内容:

{'href': '//www.autohome.com.cn/news/201810/923421.html#pvareaid=102624'}
//www.autohome.com.cn/news/201810/923421.html#pvareaid=102624
<h3>又增悍将 曝吉利全新纯电动GE11谍照</h3>

 

猜你喜欢

转载自blog.csdn.net/u011146423/article/details/82978123