【问题标题】:Why my selenium code isn't showing any text?为什么我的硒代码没有显示任何文字?
【发布时间】:2020-06-18 07:50:13
【问题描述】:

我想用 selenium 抓取整个网站。我在网站上获得了一类产品名称。我只想将所有产品名称放在一个类名下。无需为每个产品手动复制任何 id 或 XPATH。 我已经这样做了,但是:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

driver_exe = 'chromedriver'
options = Options()
options.add_argument("--headless")
driver = webdriver.Chrome(executable_path=r"C:\Users\intel\Downloads\Setups\chromedriver.exe", options=options)

driver.get("https://www.justdial.com/Bangalore/Bakeries")
x = driver.find_elements_by_class_name("store-name")

for i in x:
    print(i.text)

它没有显示任何内容。为什么???任何像美丽汤这样的解析器也将被接受 mixed 与硒,但无论如何我想要硒......

【问题讨论】:

    标签: python python-3.x selenium selenium-webdriver


    【解决方案1】:

    在无头模式解决方案中绕过Access Denied,使用不同的用户代理reference。您可以使用自己的用户代理,谷歌“我的用户代理”来获取它。

    user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) ' \
                 'Chrome/80.0.3987.132 Safari/537.36'
    driver_exe = 'chromedriver'
    options = ChromeOptions()
    options.add_argument("--headless")
    options.add_argument(f'user-agent={user_agent}')
    driver = webdriver.Chrome(options=options)
    
    driver.get("https://www.justdial.com/Bangalore/Bakeries")
    x = driver.find_elements_by_class_name("store-name")
    
    for i in x:
        print(i.text)
    

    使用

    from bs4 import BeautifulSoup
    import requests
    
    user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) ' \
                 'Chrome/80.0.3987.132 Safari/537.36'
    
    response = requests.get('https://www.justdial.com/Bangalore/Bakeries', headers={'user-agent': user_agent})
    soup = BeautifulSoup(response.text, 'lxml')
    stores = soup.select('.store-name')
    for store in stores:
        print(store.text.strip())
    

    输出:

    Big Mishra Pedha
    Just Bake
    The Cake Factory
    Queen Of Cakeland
    SREENIVASA BRAHMINS BAKERY ..
    Aubree Eat Play Love Chocol..
    Jain Bakes
    Ammas Pastries
    Facebake
    Holige Mane Brahmins Bakery
    

    【讨论】:

    • 好吧,我们不能把这段代码和 selenium 混合,或者你能纠正我的 selenium 代码吗? @Sers
    • 您可以使用请求来完成所有工作 - 更快/更轻/更好的报废解决方案。对于 Selenium,我更新了答案
    • 在这样做的同时也向我展示了"Access to image at 'https://akam.cdn.jdmagicbox.com/images/icontent/jdrwd/drop_down_arrow.svg' from origin 'https://www.justdial.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.", source: https://www.justdial.com/Bangalore/Bakeries (0) [0305/223220.362:INFO:CONSOLE(425)] "1", source: https://static.127777.com/mnbldr/?b=jd_rwd/public/minjs&g=cmnjs,usrjs,envtjs,tranlatejs,rsljs&ver_=46.80 (425)
    猜你喜欢
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多