总共分为四部分:
1.获得网页URL
2.获得网页数据
3.过滤数据,获得需要的数据
4.完整代码
一,获得网页URL
#先导入库
import urllib.request,urllib.error
from bs4 import BeautifulSoup
import re
#建立一个主函数,该代码都所有函数都在主函数执行
def main():
baseurl="https://sjz.ke.com/ershoufang/pg/" #获得贝壳网网址
def Geturl(baseurl):
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.59"}
repo=urllib.request.Request(baseurl,headers=headers)
html=''
try:
reponse=urllib.request.urlopen(repo)
html=reponse.read().decode("utf-8")
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
return html
User-Agent数据在右击检查中的network里面截取:
如果