【发布时间】:2021-10-29 19:45:46
【问题描述】:
我正在尝试使用 Python Selenium 从this 个人资料上的“关注者”按钮列表中抓取用户名。我不能这样做有两个原因:
- 我无法使用
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")滚动列表,因为列表有2 个滚动条(我不知道为什么它有2 个)。如果我尝试滚动,它会滚动个人资料页面,而不是实际列表。 - 即使我设法滚动列表,我应该如何存储用户名?用户是动态加载的,由于某种原因,类 id 看起来像这样
class='st--c-PJLV st--c-dhzjXW st--c-edagZx'
我已经尝试了几种方法来解决这个问题,但我无法达到我想要的结果,感谢任何帮助。以下是我尝试使用的一些代码 sn-ps,但出现错误:
scrollElem = driver.find_elements(By.XPATH, "//div[@class='st--c-PJLV st--c-dhzjXW st--c-
edagZx']/a")
followernumber = 2000
scrollElem[len(scrollElem)-1].location_once_scrolled_into_view
for i in range(0,followernumber):
new = len(scrollElem)+i
newname = driver.find_element(By.XPATH, "(//div[@class='st--c-PJLV st--c-dhzjXWstedagZx']/a)[%i]"%new)
print(newname.text, i)
newname.location_once_scrolled_into_view
time.sleep(1)
得到错误:selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"(//div[@class='st--c-PJLV st--c-dhzjXW st--c-edagZx']/a)[47]"}
我还尝试使用此算法在列表底部滚动并在加载时存储元素,但这也不起作用:
def scrollDown():
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(SCROLL_PAUSE_TIME)
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
算法滚动了个人资料页面,而不是关注者列表
如果我是网络抓取的新手,我将不胜感激!
【问题讨论】:
标签: python selenium web-scraping