import requests
from bs4 import BeautifulSoup
import re
geturl = 'https://sh.lianjia.com/ershoufang/rs/'
head = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36'
headers ={'User-Agent':head};
link = requests.get(url=geturl,headers=headers)
#用浏览器头访问,否则返回403
#soup = BeautifulSoup(link.text,"lxml")
#sou = soup.find('div',class_ ='unitPrice')
pattern = r'data-price="(.*?)"'
#正则表达式原来要这么写,然后传入findall中
rs = re.findall(pattern,link.text)
for detail in rs:
print(detail)
注意findall后面是正则的语句,第二个参数应该是字符串。
第一次用的时候将soup传入了参数中,果断报错了。后来大佬帮忙debug发现了这里不对。
结果即为第一页每平方的价格的输出
访问网页的时候必须得传入参数头,否则返回403,好像是反爬虫的机制。
一般第三个参数是可以更改ip