[英]How to save web scraped data from selenium to a .txt file
我對 Python 還很陌生,剛剛完成了“用 Python 自動化無聊的東西”課程。 我有一個腳本,可以很好地訪問一個站點,獲取我需要的所有必要數據,並將其打印到我的控制台。 我在如何實際將該數據保存/導出到文件時遇到了問題。 現在我希望能夠將其導出為 .txt 或 .csv 文件。 感謝任何幫助,因為我在網上找不到直接的答案。 我只需要最后一步來完成我的項目,謝謝!
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
browser = webdriver.Chrome()
def getTen():
# Opens the browser and navigates to the page
browser.get('http://taxsales.lgbs.com/map?lat=29.437693458470175&lon=-98.4618145&zoom=9&offset=0&ordering=sale_date,street_name,address_full,uid&sale_type=SALE,RESALE,STRUCK%20OFF,FUTURE%20SALE&county=BEXAR%20COUNTY&state=TX&in_bbox=-99.516502,28.71637426279382,-97.407127,30.153924134433552')
# Waits until the page is loaded then clicks the accept button on the popup window
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[2]/div/div/div[2]/button[1]"))).click()
# Loops through 10 times, changing the listing number to correspond with 1
for i in range(1,11):
clickable = "/html/body/ui-view/div[2]/main/aside/div[2]/property-listing[" + str(i) + "]/article/div/a"
# Waits until the page is loaded then clicks the view more details button on the first result
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, clickable))).click()
# Waits until the page is loaded, then pulls all the info from the top section of the page
info = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/ui-view/div/main/div/div/div[2]/property-detail-info/dl[1]")))
# prints info to the console
print(info.text);
# goes back a page and repeats the process for the next listing
browser.back()
getTen()
如果你想保存info.text
,你可以打開一個本地文件並寫入它。 例如:
with open('output.txt', 'w') as f:
f.write(info.text)
可以在此處找到有關讀取和寫入文件的更多信息: 在 Python 中讀取和寫入文件
您可以簡單地在控制台中使用輸出/獲取文本並使用以下代碼獲取文本 in.txt output.txt 將是您要保存的文件名, element.text 將是您要保存的元素或文本。文本
with open('output.txt', 'w') as f:
f.write(elements.text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.