您的位置:首页 > 产品设计 > UI/UE

requests打开网页,BeautifulSoup解析网页,得到目标网址的相对地址,urllib.parse重组url地址

2018-03-01 17:08 399 查看
requests官网:http://www.python-requests.org/en/master/user/quickstart/

BeautifulSoup官网:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#attributes

python标准库urllib.parse:https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlsplit

# 取中关村网页的第一页
import requests
r = requests.get('http://detail.zol.com.cn/cell_phone_index/subcate57_0_list_1_0_1_1_0_1.html')

# 将上一步取得的.html给BeautifulSoup解析
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.text, 'lxml')

# 找到下一页的链接
next_path = soup.find(attrs={"class": "small-page-next"})["href"]

# 解析url链接中的各个部分
from urllib.parse import urlparse
o = urlparse(r.url)

# 组合parse到的协议/网络地址,以及目的页面的相对路径
from urllib.parse import ParseResult
t = ParseResult(o.scheme, o.netloc, next_path, "","","")

# 根据重组的url集合,生成url字符串
from urllib.parse import urlunparse
next_url = urlunparse(t)

从中关村在线查找手机型号,在本地建立数据库。
网站每页显示48个手机,共39页,需要设计一个翻页程序。
上述代码获取翻页的用到的目标url,还需要加循环,将全部页遍历获得所有的手机型号。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: