【发布时间】:2020-04-29 13:00:07
【问题描述】:
我正在尝试从 sciencedirect 网站上抓取数据。 我试图通过创建一个 xpath 列表并循环它们来一个接一个地访问日志问题,从而使抓取过程自动化。 当我运行循环时,我在访问第一个日志后无法访问其余元素。 这个过程在另一个网站上对我有用,但在这个网站上不起作用。
我还想知道除了这个过程之外还有什么更好的方法来访问这些元素。
#Importing libraries
import requests
import os
import json
from selenium import webdriver
import pandas as pd
from bs4 import BeautifulSoup
import time
import requests
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#initializing the chromewebdriver|
driver=webdriver.Chrome(executable_path=r"C:/selenium/chromedriver.exe")
#website to be accessed
driver.get("https://www.sciencedirect.com/journal/journal-of-corporate-finance/issues")
#generating the list of xpaths to be accessed one after the other
issues=[]
for i in range(0,20):
docs=(str(i))
for j in range(1,7):
sets=(str(j))
con=("//*[@id=")+('"')+("0-accordion-panel-")+(docs)+('"')+("]/section/div[")+(sets)+("]/a")
issues.append(con)
#looping to access one issue after the other
for i in issues:
try:
hat=driver.find_element_by_xpath(i)
hat.click()
sleep(4)
driver.back()
except:
print("no more issues",i)
【问题讨论】:
-
meta.stackoverflow.com/q/303812/11301900。您能否分享相关的 HTML 以及一些构建的 XPath 查询?我的猜测是你甚至可能不需要循环。
-
['//*[@id="0-accordion-panel-0"]/section/div[1]/a', '//*[@id="0-accordion -panel-0"]/section/div[2]/a', '//*[@id="0-accordion-panel-0"]/section/div[3]/a', '//* [@id="0-accordion-panel-0"]/section/div[4]/a',这些是我创建的 xpath,请从sciencedirect.com/journal/journal-of-corporate-finance/issues 查找 html,我无法放置 html在 cmets 中。谢谢
-
无论如何,这些都不应该在 cmets 中,您可以编辑您的帖子。查看这些 XPath 查询,您确实应该能够使用单个带有
.find_elements_by_xpath()的查询。
标签: python selenium selenium-webdriver web-scraping webdriverwait