注册 登录
编程论坛 Python论坛

求教,关于python正则表达式的问题

xzjy789 发布于 2019-07-10 08:36, 1612 次点击
我在使用爬虫爬取网页源代码后,希望利用正则表达式提取出指定内容,具体情况如下:
网页源代码,其中红框内的文字是我要的内容
只有本站会员才能查看附件,请 登录

爬取网页的代码如下:
weburl="http://

req=urllib.request.Request(url=weburl)
response=urllib.request.urlopen(req)
content = response.read()
#获得系统的编码
type = sys.getfilesystemencoding()
#设置爬出内容的编码
content = content.decode(type)

求教各位大神,如何爬取我要的内容?如果可以,请写出完整的代码,不要只写正则表达式,小白一个,谢谢各位
3 回复
#2
wp2319572019-07-10 09:49
这类的使用正则 并不是最优选择

程序代码:

# coding: utf-8

import requests
from lxml import etree

agent = "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
headers = {'User-Agent':agent}   
url="http://"
res = requests.get(url,headers=headers,timeout=5)
html = etree.HTML(res.text)
data=html.xpath("/html/body/dd[20]/span[1]/a")
print(data[0].text)

'''
e:\pytest>python ex6.py

                基于EKC的中国人均CO
               
'''
#3
wp2319572019-07-10 11:01
回复 楼主 xzjy789
2楼代码有些问题 ,现在更换bs4 选择器
 
程序代码:


# coding: utf-8

import requests
from bs4 import BeautifulSoup as bs

agent = "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0"
headers = {'User-Agent':agent}   
url="http://"
res = requests.get(url,headers=headers,timeout=5)
soup = bs(res.text, "lxml")
sp=soup.find_all("span",class_="name")
for x in sp:print(x.get_text())



#4
xzjy7892019-07-10 11:05
回复 4楼 wp231957
非常感谢,我也查询了一下,对于这类使用BS4是最优选择,谢谢使用BS4为我写了范例代码
1