【发布时间】:2021-05-04 12:30:58
【问题描述】:
我正在尝试使用 selenium python 从 Youtube 抓取数据。我正在抓取的数据具有订阅者、位置、加入和视图等字段。尽管给出了正确的 xpath,但我得到了这样的错误
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="subscriber-count"]"}
(Session info: chrome=90.0.4430.93)
我尝试过的方法是使用 css_selectors、完整的 xpath、id、类名,但它们都没有真正起作用。都返回与上述相同的错误。
这是我在 python 脚本中的编写方式:
youtube_subscribers = browser.find_element_by_xpath('//*[@id="subscriber-count"]').text
youtube_location = browser.find_element_by_xpath('//*[@id="details-container"]/table/tbody/tr[2]/td[2]/yt-formatted-string').text
youtube_joined_on = browser.find_element_by_xpath('//*[@id="right-column"]/yt-formatted-string[2]/span[2]').text
youtube_views = browser.find_element_by_xpath('//*[@id="right-column"]/yt-formatted-string[3]').text
print('Youtube Subscribers:', youtube_subscribers)
print('Youtube Location:', youtube_location)
print('Youtube Joined on:', youtube_joined_on)
print('Youtube views:', youtube_views)
我正在从这里抓取https://www.youtube.com/c/adidas/about。我到底哪里错了?
请帮忙!
编辑:这是相同的完整代码。
website = ['https://www.pinterest.com/adidas/', 'https://www.pinterest.com/nike/', 'https://www.pinterest.com/puma/']
options = webdriver.ChromeOptions()
options.add_argument('start-maximized')
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)
delays = [7, 4, 6, 2, 10, 19]
delay = np.random.choice(delays)
for crawler in website:
browser.get(crawler)
time.sleep(2)
time.sleep(delay)
pinterest_brand_name = browser.find_element_by_xpath('/html/body/div[1]/div[1]/div/div/div[1]/div[1]/div[2]/div/div/div/div[2]/div/div/h1').text
pinterest_followers = browser.find_element_by_xpath('/html/body/div[1]/div[1]/div/div/div[1]/div[1]/div[2]/div/div/div/div[2]/div/div/div[2]/div/span[1]').text
pinterest_following = browser.find_element_by_xpath('/html/body/div[1]/div[1]/div/div/div[1]/div[1]/div[2]/div/div/div/div[2]/div/div/div[2]/div/div[1]/span[1]').text
youtube_subscribers = browser.find_element_by_xpath('//*[@id="subscriber-count"]').text
youtube_location = browser.find_element_by_xpath('//*[@id="details-container"]/table/tbody/tr[2]/td[2]/yt-formatted-string').text
youtube_joined_on = browser.find_element_by_xpath('//*[@id="right-column"]/yt-formatted-string[2]/span[2]').text
youtube_views = browser.find_element_by_xpath('//*[@id="right-column"]/yt-formatted-string[3]').text
print('Pinterest Brand Name:', pinterest_brand_name)
print('Pinterest Followers:', pinterest_followers)
print('Pinterest Following:', pinterest_following)
print('Youtube Subscribers:', youtube_subscribers)
print('Youtube Location:', youtube_location)
print('Youtube Joined on:', youtube_joined_on)
print('Youtube views:', youtube_views)
【问题讨论】:
标签: python selenium selenium-webdriver web-scraping