一、前提声明
1、逐行清除符号
names = [i.strip() for i in resp.xpath('//div[@class="nlcd_name"]/a/text()')]
二、完整代码及结果
1、代码
import requests
import pandas
from lxml import etree
for i in range(1,6):
#获取5页数据
url = f'https://yl.newhouse.fang.com/house/s/b1dianpingdes-b9{i}/'
heardes = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'}
respond = requests.get(url,headers=heardes)
#print(respond.text)
resp = etree.HTML(respond.text)
names = [i.strip() for i in resp.xpath('//div[@class="nlcd_name"]/a/text()')]
addres = [i.strip() for i in resp.xpath('//div[@class="address"]/a/@title')]
prices = [i.xpath('string(.)').strip() for i in resp.xpath('//div[@class="nhouse_price"]')]
data = []
for n,a,p in zip(names,addres,prices):
print(f'{n}---地址:{a}----售价:{p}')
data.append([n,a,p])
df = pandas.DataFrame(data,columns=['楼盘名','地址','价格'])
print(df)
2、结果
三、优化后的代码
1、将数据写入xlsx表格
import requests
import pandas as pd
from lxml import etree
data = [] # 用于存储数据
for i in range(1, 6):
# 获取5页数据
url = f'https://yl.newhouse.fang.com/house/s/b1dianpingdes-b9{i}/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Failed to fetch data from page {i}")
continue
resp = etree.HTML(response.text)
names = [i.strip() for i in resp.xpath('//div[@class="nlcd_name"]/a/text()')]
addresses = [i.strip() for i in resp.xpath('//div[@class="address"]/a/@title')]
prices = [i.xpath('string(.)').strip() for i in resp.xpath('//div[@class="nhouse_price"]')]
data.extend(zip(names, addresses, prices))
# 一次性写入Excel文件
df = pd.DataFrame(data, columns=['楼盘名', '地址', '价格'])
df.to_excel('玉林房价.xlsx', index=False)
print(df)
2、结果
3、逐行解释
import requests
import pandas as pd
from lxml import etree
data = [] # 用于存储数据
- 导入所需的库,包括requests用于HTTP请求,pandas用于处理数据,以及lxml用于解析HTML。
- 创建一个空列表
data
,用于存储从网页中提取的数据。
for i in range(1, 6):
# 获取5页数据
url = f'https://yl.newhouse.fang.com/house/s/b1dianpingdes-b9{i}/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}
- 使用循环遍历从1到5的页面编号,构建每个页面的URL。
- 设置HTTP请求的头部信息,包括用户代理(User-Agent)。
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Failed to fetch data from page {i}")
continue
- 使用
requests.get()
方法发送HTTP GET请求以获取页面内容。 - 检查HTTP响应状态码,如果不等于200(成功),则输出失败消息并跳过当前页面的处理
resp = etree.HTML(response.text)
names = [i.strip() for i in resp.xpath('//div[@class="nlcd_name"]/a/text()')]
addresses = [i.strip() for i in resp.xpath('//div[@class="address"]/a/@title')]
prices = [i.xpath('string(.)').strip() for i in resp.xpath('//div[@class="nhouse_price"]')]
- 使用lxml库解析HTTP响应文本,创建一个XML或HTML文档树,以便执行XPath查询。
- 通过XPath查询提取页面中的楼盘名称、地址和价格,将它们分别存储在名为
names
、addresses
和prices
的列表中。 i.xpath('string(.)')
表达式用来提取该元素的文本内容。这是通过XPath表达式string(.)
来实现的。string(.)
表达式会获取指定元素及其子元素的所有文本内容,并将其合并成一个字符串。
代码prices = [i.xpath('string(.)').strip() for i in resp.xpath('//div[@class="nhouse_price"]')]又可以写成:
prices = []
for div_element in resp.xpath('//div[@class="nhouse_price"]'):
price_text = div_element.xpath('string(.)')
cleaned_price = price_text.strip()
prices.append(cleaned_price)
注意,如果只输出resp.xpath('//div[@class="nhouse_price"]'),得到的是参数,加上/text()也没用
data.extend(zip(names, addresses, prices))
使用zip()
函数将每个页面中提取的楼盘名称、地址和价格合并为一个元组,并将这些元组添加到data
列表中。
df = pd.DataFrame(data, columns=['楼盘名', '地址', '价格'])
df.to_excel('玉林房价.xlsx', index=False)
print(df)
- 一次性将
data
列表中的数据创建为一个Pandas DataFrame,为每列指定列名。 - 使用
to_excel()
方法将DataFrame的内容写入名为'玉林房价.xlsx'的Excel文件,同时通过index=False
指定不保存行索引。 - 最后,输出DataFrame以查看提取的数据。