【问题标题】:Can't find a div that exists with 'inspect element' while scraping a website在抓取网站时找不到存在“检查元素”的 div
【发布时间】:2018-01-18 03:57:47
【问题描述】:

我有一个下载 html 页面的 python 脚本。我正在寻找这个 div:

<data-a-target="clip-thumbnail-link"  

当我检查我看到的网页上的元素时,那个 div 就在那里。但它没有出现在我的脚本中的打印语句中

from bs4 import BeautifulSoup
from urllib import urlopen

BASE_URL = "https://www.twitch.tv/lethalfrag/clips"

def get_category_links(section_url):
    html = urlopen(section_url).read()    
    soup = BeautifulSoup(html, "lxml")    
    print(soup)     

get_category_links(BASE_URL)

【问题讨论】:

  • 听起来该元素是通过 javascript 基于某些事件(鼠标悬停、鼠标单击或简单的计时器)注入到页面内容中的。
  • 您可能想了解 Selenium。

标签: python web-scraping beautifulsoup


【解决方案1】:

如果您在页面源中搜索检查过的元素,您会发现它丢失了。这告诉我们 JavaScript 在加载后正在修改页面。 urllibrequests 无法运行 JavaScript 代码。所以,你必须使用Selenium

有关安装和演示,请阅读此https://pypi.python.org/pypi/selenium

您需要使用explicit wait 来获取您要查找的元素。

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome()
driver.get('https://www.twitch.tv/lethalfrag/clips')
try:
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'clips-cards ')))
except TimeoutException:
    print('Page timed out after 10 secs.')
soup = BeautifulSoup(driver.page_source, 'html.parser')
driver.quit()
print(soup.find('a', {'data-a-target': 'clip-thumbnail-link'})['href'])  

输出:

https://clips.twitch.tv/RealIgnorantHeronVoteYea

【讨论】:

  • 为网站“usana.com”尝试上述代码,(href 在检查中可见,但在页面源中不可见)但似乎不起作用。我需要其文本包含“联系人”一词的href。你能帮忙吗!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-05
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 2020-03-24
相关资源
最近更新 更多