【发布时间】:2017-06-29 04:03:04
【问题描述】:
我正在尝试从https://icostats.com/ 的首页表格中获取数据。但是有些东西没有点击。
from selenium import webdriver
browser = webdriver.Chrome(executable_path=r'C:\Scrapers\chromedriver.exe')
browser.get("https://icostats.com")
browser.find_element_by_xpath("""//*[@id="app"]/div/div[2]/div[2]/div[2]/div[2]/div[8]/span/span""").s()
posts = browser.find_element_by_class_name("tdPrimary-0-75")
for post in posts:
print(post.text)
我遇到的错误:
*
C:\Python36\python.exe C:/.../PycharmProjects/PyQtPS/ICO_spyder.py Traceback(最近一次通话最后一次):文件 “C:/.../PycharmProjects/PyQtPS/ICO_spyder.py”,第 5 行,在 browser.find_element_by_xpath("""//[@id="app"]/div/div[2]/div[2]/div[2]/div[1]/div[2]""" )。点击() 文件 "C:\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", 第 313 行,在 find_element_by_xpath 中 return self.find_element(by=By.XPATH, value=xpath) 文件 "C:\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", 第 791 行,在 find_element 中 'value': value})['value'] 文件 "C:\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", 第 256 行,执行中 self.error_handler.check_response(response) 文件 "C:\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", 第 194 行,在 check_response 中 raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such 元素:无法定位元素: {"method":"xpath","selector":"//[@id="app"]/div/div[2]/div[2]/div[2]/div[1] /div[2]"} (会话信息:chrome=59.0.3071.115)(驱动程序信息: 铬驱动程序=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),平台=Windows NT 6.1.7600 x86_64)
*
编辑
终于搞定了:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait
browser = webdriver.Chrome(executable_path=r'C:\Scrapers\chromedriver.exe')
browser.get("https://icostats.com")
wait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#app > div > div.container-0-16 > div.table-0-20 > div.tbody-0-21 > div:nth-child(2) > div:nth-child(8)")))
posts = browser.find_elements_by_class_name("thName-0-55")
for post in posts:
print(post.text)
posts = browser.find_elements_by_class_name("tdName-0-73")
for post in posts:
print(post.text)
有没有办法遍历每个标题/列并将其导出到 csv 文件,而不必像这样遍历每个类?
【问题讨论】:
-
从网站上我可以看到 id app 的 div 内没有其他 div?那你怎么试?你在尝试什么?
-
这显然与
xpath有关,您确定网站的HTML结构中包含这些元素吗? -
是的,我还直接从 Chrome 中复制了 xpath。
标签: javascript python selenium web-scraping