簡體   English   中英

在 Python 中使用 Selenium,通過 xpath、.text 使用查找元素進行網頁抓取

[英]Using Selenium in Python, webscraping using find elements by xpath, .text

我正在嘗試使用 Python 和 Selenium 自動執行每周必須執行的任務。

我訪問一個網站,如果有任何新文件,我會下載它們,使用它們進來的日期和去的人重命名它們,然后將它們放在共享網絡服務器上的文件夾中。

該網站通過可點擊的鏈接提供文件進入的日期。

通過 xpath 使用 find 元素,我假設是參數,開始和包含,我已經能夠搜索所有帶有日期和時間的鏈接。

receivedTime = browser.find_elements_by_xpath('//*[starts-with(@id, 
"anchor") and contains(@id, "_0")]')
for time in receivedTime:
 print(time.text)

輸出看起來像這樣,例如,“11/2/2018, 8:00:50 AM”。

我想將該文本格式化為“2018-11-02”,我該怎么做?

我的理解是變量time只是 Current Xpath 的一個對象,而 .text 只是該對象的一個​​屬性。 我的理解正確嗎?

謝謝你。

回答:

receivedTime = browser.find_elements_by_xpath('//*[starts-with(@id, 
"anchor") and contains(@id, "_0")]')
for time in receivedTime:
 date = str(time.text).split(',')
 dateTime = datetime.strptime(date[0], '%m/%d/%Y').strftime('%Y-%m-%d-')
 print(dateTime)

您應該使用包datetime ( import datetime )
時間變量是一個字符串,因此您必須將其轉換為日期時間並像這樣更改格式:

date = str(time.text).split(',')
datetime.datetime.strptime(date[0], '%m/%d/%Y').strftime('%Y-%m-%d')

您還可以使用正則表達式來提取數字並重新格式化日期:

import re
text = "11/2/2018, 8:00:50 AM"
date_tuple = re.match("(\d+)\/(\d+)\/(\d+)", text).groups()
file_name = "%d-%02d-%02d" % (int(date_tuple[2]), int(date_tuple[0]), int(date_tuple[1]))

結果:“2018-11-02”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM