python-3.x - 如何将这些 Web 剪贴的数据导出到 csv 文件中?
问题描述
我对编码和网络抓取很陌生,我一直在 youtube 上观看大量教程,但找不到将这些数据写入 csv 文件的方法。有人可以帮忙吗?
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
options = Options()
options.add_argument("window-size=1400,600")
from fake_useragent import UserAgent
ua = UserAgent()
a = ua.random
user_agent = ua.random
print(user_agent)
options.add_argument(f'user-agent={user_agent}')
driver = webdriver.Chrome('/Users/raduulea/Documents/chromedriver', options=options)
driver.get('https://www.immoweb.be/fr/recherche/immeuble-de-rapport/a-vendre')
import time
time.sleep(10)
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
results = soup.find_all("div", {"class":"result-xl"})
for result in results:
print(result.find("div", {"class":"title-bar-left"}).get_text())
print(result.find("span", {"result-adress"}).get_text())
print(result.find("div", {"class":"xl-price rangePrice"}).get_text())
print(result.find("div", {"class":"xl-surface-ch"}).get_text())
print(result.find("div", {"class":"xl-desc"}).get_text())
解决方案
用于pandas DataFrame
在其中添加数据。然后导出为更容易的 CSV 文件。
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
options = Options()
options.add_argument("window-size=1400,600")
from fake_useragent import UserAgent
ua = UserAgent()
a = ua.random
user_agent = ua.random
print(user_agent)
options.add_argument(f'user-agent={user_agent}')
driver = webdriver.Chrome('/Users/raduulea/Documents/chromedriver', options=options)
driver.get('https://www.immoweb.be/fr/recherche/immeuble-de-rapport/a-vendre')
import time
time.sleep(10)
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
results = soup.find_all("div", {"class":"result-xl"})
title=[]
address=[]
price=[]
surface=[]
desc=[]
for result in results:
title.append(result.find("div", {"class":"title-bar-left"}).get_text().strip())
address.append(result.find("span", {"result-adress"}).get_text().strip())
price.append(result.find("div", {"class":"xl-price rangePrice"}).get_text().strip())
surface.append(result.find("div", {"class":"xl-surface-ch"}).get_text().strip())
desc.append(result.find("div", {"class":"xl-desc"}).get_text().strip())
df = pd.DataFrame({"Title":title,"Address":address,"Price:":price,"Surface" : surface,"Description":desc})
df.to_csv("output.csv")
输出:您的 csv 文件将是这样的。
推荐阅读
- javascript - Vuex状态在突变后不更新
- batch-file - 批量重命名文件,合并列.csv?
- python - 为什么我无法使用 clf(**params) 解压 sklearn 模型的参数?
- c# - 查询具有远程计算的相关实体计数的实体
- postgresql - 在 sql 转储中设置 search_path
- javascript - 拆分 2 个不同长度的字符串返回相同的值
- android - 无引用复制ArrayList对象快速解决方案
- javascript - 如何发送列表对象而不是单个对象
- continuous-integration - gocd - 代理从不做第二个管道阶段/工作
- python - 使用决策树的自定义数据预测