python爬虫_1

urllib模块,内置模块

from urllib.request import urlopen

url = '网址(https://baike.baidu.com)'

html = urlopen(url).read().decode('utf-8') #如果有中文就要使用utf-8

print(html) #查看输出结果

re模块,使用正则表达式

import re

#找出第一个<title></title>标签里的内容
title1 = re.find(r'<title>(.*?)</title>',html)

#找出所有<title></title>标签里的内容
title2 = re.findall(r'<title>(.*?)</title>',html)

#查看结果
print(title1)
print(title2)
print(title2[0])

#找出所有<p></p>标签里的内容
p = re.findall(r'<p>(.*?)</p>',html,flags = re.DOTALL)
#re.DOTALL 允许多行,(.*?)为匹配内容

print(p)

使用bs4模块,比正则表达式容易使用

Python 2+

pip install beautifulsoup4

Python 3+

pip3 install beautifulsoup4
from bs4 import BeautifulSoup
from urllib.request import urlopen
import lxml

url = '网址(https://baike.baidu.com)'
html = urlopen(url).read().decode('utf-8')

soup = BeautifulSoup(html,features="lxml")#使用lxml的方式解析网页
#输出<p></p>标签的内容
print(soup.p)

a = soup.find_all('a')#找到所有a标签
#循环输出a中的网址
for i in a:
    print(i[href])

BeautifulSoup 中的 find_all() 可以添加参数

soup = BeautifulSoup(html,features='lxml')
month = soup.find_all('li',{'class':'month'})#如:<li class="month">一月</li>

print(month.get_text())#一月

img_links = soup.find_all('img',{'src':re.compile('.*?\.jpg')})
for i in img_links:
  print(i['src'])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值