【发布时间】:2019-08-01 01:16:19
【问题描述】:
我正在尝试从 kicksusa.com 抓取数据,但遇到了一些问题。
当我尝试像这样的基本 BS4 方法时(导入是从使用所有这些的主程序复制/粘贴的):
import requests
import csv
import io
import os
import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from datetime import datetime
from bs4 import BeautifulSoup
data1 = requests.get('https://www.kicksusa.com/')
soup1 = BeautifulSoup(data1.text, 'html.parser')
button = soup1.find('span', attrs={'class': 'shop-btn'}).text.strip()
print(button)
结果是“无”,这告诉我数据是通过 JS 隐藏的。所以,我尝试使用 Selenium,如下所示:
options = Options()
options.headless = True
options.add_argument('log-level=3')
driver = webdriver.Chrome(options=options)
driver.get('https://www.kicksusa.com/')
url = driver.find_element_by_xpath("//span[@class='shop-btn']").text
print(url)
driver.close()
我得到“无法找到元素”。
有人知道如何使用 BS4 或 Selenium 抓取该网站吗?提前谢谢!
【问题讨论】:
-
您的 selenium 代码是正确的,并且适用于 Firefox 驱动程序。
print(driver.find_element_by_xpath("//span[@class='shop-btn']").text)使用 Firefox 驱动程序输出“Shop Puma”。也许这是无头镀铬的问题?您还应该尝试在get和find_element_by_xpath之间超时。 -
您实际需要哪些数据?只是像shop puma之类的文字?还是您打算点击按钮?
-
@nmb.ten - 这很奇怪,同样的代码适用于另一个 URL/网站上的 Chrome 驱动程序。我会尝试添加超时,谢谢您的输入。
-
@QHarr - 我只是想获取文本,上面的 sn-p 只是我尝试获取任何数据时的一个例子(我在 a.hrefs 的 div 类之后)项目”在这个exact URL 上——然后我会将hrefs 提供给一个循环,打开它们并获取品牌和型号)
标签: python selenium selenium-webdriver web-scraping beautifulsoup