不加延迟报错selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":".//span[@class="DyListCover-hot"]"}
(Session info: chrome=80.0.3987.122)
![](http://47.103.208.64/wp-content/uploads/2020/03/image-1024x47.png)
然后我注释掉这一段
![](http://47.103.208.64/wp-content/uploads/2020/03/image-1-1024x153.png)
然后报Message: stale element reference: element is not attached to the page document
![](http://47.103.208.64/wp-content/uploads/2020/03/image-2-1024x78.png)
但是却爬取到一段消息
![](http://47.103.208.64/wp-content/uploads/2020/03/image-3-1024x260.png)
说明有可能是延时的问题,在开头加上延时,成功解决
附上源码 import json import timefrom selenium import webdriver
driver=webdriver.Chrome()
driver.get("https://www.**yu.com/directory/all")
****# driver.close()****
#
def douyu():
##要加延迟,不然要报错
time.sleep(5)
li_list=driver.find_elements_by_xpath('//*[@id="listAll"]/section[2]/div[2]/ul/li')
# print(list_all)
content_dict={}
for li in li_list:
content_dict["title"]=li.find_element_by_xpath(".//h3").text
content_dict["belong"]=li.find_element_by_xpath('.//span[@class="DyListCover-zone"]').text
content_dict["watch_num"]=li.find_element_by_xpath('.//span[@class="DyListCover-hot"]').text
content_dict["author"] = li.find_element_by_xpath(".//h2").text
print(content_dict)
#将字典转换为字符串便于存储
s=json.dumps(content_dict,ensure_ascii=False) #json序列化默认对中文采用ascii编码,所以False
with open("douyu.txt","a",encoding="utf-8") as f:
f.write(s+'\n')
next_url=driver.find_elements_by_xpath('//li[@title="下一页"]/span[@class="dy-Pagination-item-custom"]')
#三元表达式
next_url=next_url[0] if len(next_url) > 0 else None
while next_url is not None:
next_url.click()
time.sleep(3)
#我调我自己 点击下一页停5s继续爬取 延时设在开头
douyu()
douyu()