python webscraping:您无权访问此资源

时间:2021-05-14 02:14:51

标签: python selenium headless

我需要抓取一个“无头”格式的网站,因为我不想看到弹出的窗口。 如果网站可见,下面的代码有效,但不能作为无头工作,表明我没有权限:

“拒绝访问

您无权访问“http://www.hoteis.com/ho402825/?”在这台服务器上。

参考 #18.563106c9.1620956860.1bad747"

代码是:

    def search():
            link = (
            https://www.infomoney.com.br/
            )

            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
            chrome_options.add_argument('--headless')
            driver = webdriver.Chrome('chromedriver', options = chrome_options)
            driver.get(link)
            element = driver.find_element_by_tag_name('body')
            resposta = element.get_attribute('innerHTML') 
            site = BeautifulSoup(resposta, 'html.parser')
            return driver, site

我看到一些问题说要在我的代码上应用“标头”,但是当我使用 webdriver 时,我认为它不起作用。

    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}

2 个答案:

答案 0 :(得分:0)

知道您尝试抓取的网站是否允许执行此操作吗?

在以下位置找到任何网站抓取规则: 任何www.site.com/robots.txt

例如:

www.google.com

www.google.com/robots.txt

www.facebook.com

www.facebook.com/robots.txt

robots.txt 帮助:

https://www.infocompile.com/how-to-view-robots-txt-file-of-any-website/

答案 1 :(得分:0)

如果您想在无头模式下抓取整个网页,有很多方法。您调用使用下面的 css 选择器作为 body 标签并使用 'outerHTML' 属性。

代码:

options = webdriver.ChromeOptions()
options.add_argument('start-maximized')
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument('--headless')
driver = webdriver.Chrome("C:\\Users\\etc\\Desktop\\Selenium+Python\\chromedriver.exe", options=options)
wait = WebDriverWait(driver, 30)
driver.get("https://www.infomoney.com.br/")
element = driver.find_element_by_css_selector("body[class^='home page-template-default page page-id-']")
resposta = element.get_attribute('outerHTML')
print(resposta)
site = BeautifulSoup(resposta, 'html.parser')
相关问题