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'])

猜你喜欢

转载自blog.csdn.net/su_unknown_world/article/details/79402749