python-3.x - 使用 Selenium 进行 Web 抓取,使用 XPath 没有结果
问题描述
我正在尝试从https://openaq.org/#/location/Algiers?_k=nv8w8w获取数据,但它总是返回一个空值。
def getCardDetails(country, url):
local_df = pd.DataFrame(columns=['country','card_url','general','country_link','city', 'PM2.5','date','hour'])
pm = None
date = None
hour = None
general = None
city = None
country_link = None
try:
#wait = WebDriverWait(driver, 3)
#wait.until(EC.presence_of_element_located((By.ID, 'location-fold-stats')))
time.sleep(2)
# Using Xpath we are getting the full text of the sibling that comes
# after the text containing "PM2.5". We will split the full text to
# generate variables for our Data Frame such as "pm", "date" & "hour".
try:
print("inn")
pm_date = driver.find_element(By.XPATH, '//dt[text() = "PM2.5"]/following-sibling::dd[1]').text
# Scraping pollution details from each location page
# and splitting them to save in the relevant variables
text = pm_date.split('µg/m³ at ')
print("nn",pm_date)
pm = float(text[0])
full_date = text[1].split(' ')
date = full_date[0]
hour = full_date[1]
这是我第一次在网页抓取中使用 Selenium。我想知道 XPath 是如何工作的,这里有什么问题。
解决方案
您XPATH
是正确的。要从动态元素中获取值,您需要诱导WebDriverWait
() 并等待visibility_of_element_located
()
print(WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,'//dt[text() = "PM2.5"]/following-sibling::dd[1]'))).text)
推荐阅读
- javascript - Openweather.com API 5 次日预报问题
- python - Microsoft Graph API 同步 API,更新秘密令牌仅在第二次调用时有效
- html - Django URL 显示上一个和当前页面,但我只想要 URL 中的当前页面名称
- python - 属性错误:模块 tensorflow 没有属性“get_default_graph”?
- delphi - Firemonkey TFrame - 如何触发祖先 TFrame 事件?
- javascript - 是否可以将父div中的所有项目都放在列中
- java - 在 C/C++ 中获取 Kerberos 票证
- reactjs - React 转换转换组问题。想做一个简单的动画,但是不行
- r - R - 创建数据集,显示两个相似数据集之间的增量/进度
- python - DataFrameA.columnA 与 Pandas 中的 DataFrameA.["columnA"] 相同吗?