由于某些原因,我无法从html获取文本

2024-09-30 16:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

该代码在我尝试.text之前一直有效,它给我的错误是“list”对象没有属性“text”。当我将.text与同一列表中的单个元素一起使用时,它工作得非常好。我也无法获取href链接的文本。有什么想法吗

from bs4 import BeautifulSoup
import time
import requests
from selenium import webdriver

headers={

'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) 
 Chrome/72.0.3626.121 Safari/537.36'
 }


 base_url=('https://waxpeer.com/')
 driver=webdriver.Chrome()
 driver.get("https://waxpeer.com/")
 time.sleep(10)
 #driver.find_element_by_xpath('//*[@id="container"]/div[1]/div[1]/a').click()

 time.sleep(10)
 html=driver.find_elements_by_xpath('/html/body/div[1]/div/div/main/section/div[2]/div/div/div/a')
 print(html)

Tags: textfromhttpsimportdivcombytime
1条回答
网友
1楼 · 发布于 2024-09-30 16:23:16

2个问题

没有与这些XPath关联的text。我假设您要打印每个项目的URL

此外,您不能直接从列表中访问它。您需要对其进行迭代

html = driver.find_elements_by_xpath("//div[@class='lpd_div']/a")

for item in html:
    print(item.get_attribute("href"))


https://waxpeer.com/sport-gloves-vice-field-tested/item/21642893513
https://waxpeer.com/karambit-gamma-doppler-factory-new/item/21733106690
https://waxpeer.com/karambit-gamma-doppler-factory-new/item/21733106719
...

请注意,我将您的xPath缩短为一个更易于管理的

如果要打印项目说明,请使用此

html = driver.find_elements_by_xpath("//div[@class='lpd_div']/div[2]/p")
for item in html:
    print(item.text)

★ Sport Gloves
Field-Tested
★ Karambit
...
  

相关问题 更多 >