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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值