如何解决由bs4和regex元素创建的pandas对象被打印为python列表
我正在从zoopla.co.uk抓取房屋数据
我正在获取所需的数据,但是三个元素作为python列表被打印到csv文件和数据帧中。 bathrooms
和bedrooms
这两个元素是字符串,因此可以正确打印,但是使用正则表达式house_price
,house_type
和{{1 }}打印为列表类型。
我应该不使用正则表达式,而仅使用bs4吗?我不能只是简单地使用替换功能,对吗?预先感谢。
代码
station_distance
输出
import requests
from bs4 import BeautifulSoup
import re
import pandas as pd
my_url = 'https://www.zoopla.co.uk/for-sale/property/b23/?page_size=100&q=B23&radius=0&results_sort=newest_listings&search_source=refine'
res = requests.get(my_url)
soup = BeautifulSoup(res.text,"html.parser")
lis = soup.find("ul",class_="listing-results clearfix js-gtm-list").find_all("li",class_="srp clearfix")
for li in lis:
bedrooms = li.find("span",class_="num-beds")
bathrooms = li.find("span",class_="num-baths")
price = li.find("a",class_="text-price")
house_price = re.findall('\£(\d+)',str(price))
style = li.find("h2",class_="listing-results-attr")
house_type = re.findall('(?<=bed ).*(?= for)',str(style))
distance = li.find("li",class_="clearfix")
station_distance = re.findall('\d+\.?\d*',str(distance))
if bedrooms:
bedrooms = bedrooms.get_text(strip=True)
if bathrooms:
bathrooms = bathrooms.get_text(strip=True)
if house_price:
house_price = house_price
if house_type:
house_type = house_type
if station_distance:
station_distance = station_distance
df = pd.DataFrame({'house_price': house_price,'house_type': house_type,'station_distance': station_distance,'bedrooms': bedrooms,'bathrooms': bathrooms})
print(df)
df.to_csv('zoopla.csv')
解决方法
它们像列表一样打印,因为您使用的是 findall ,
house_price = re.findall('\£(\d+)',str(price))
house_type = re.findall('(?<=bed ).*(?= for)',str(style))
station_distance = re.findall('\d+\.?\d*',str(distance))
您可以保留第一个元素(在每个 if 内部)
house_price = house_price[0]
house_type = house_type[0]
station_distance = station_distance[0]
或尝试查找(就像您使用浴室和卧室一样)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。