【问题标题】:How to render JS to generate fingerprint for cookie?如何渲染 JS 为 cookie 生成指纹?
【发布时间】:2019-10-22 22:33:24
【问题描述】:

本网站使用JS设置cookie。

如何运行 JS 来模拟浏览器以避免 429 错误?

from requests_html import HTMLSession

with HTMLSession() as s:
  url = 'https://www.realestate.com.au/auction-results/nsw'
  r = s.get(url)
  print(r.status_code)
  print(r.text)

  r.html.render()
  print(r.text)

【问题讨论】:

    标签: javascript python cookies puppeteer python-requests-html


    【解决方案1】:

    如果没有某种形式的浏览器模拟,似乎几乎不可能绕过指纹(即使使用 seleniumm,我也必须设置一些选项)。这是我想出的使用 Selenium 获取发出请求所需的唯一关键信息(名为“FGJK”的 cookie)的方法,该信息在后续请求标头中发送,并异步获取所有郊区结果页面。

    from requests_html import AsyncHTMLSession
    import asyncio
    from selenium import webdriver
    import nest_asyncio
    
    #I'm using IPython which doesn't like async unless the following is applied:
    nest_asyncio.apply()
    
    async def get_token():
        options = webdriver.ChromeOptions()
        options.add_experimental_option('excludeSwitches', ['enable-automation']) 
        driver = webdriver.Chrome(options=options)
        driver.get('https://www.realestate.com.au/auction-results/nsw')
        cookies = driver.get_cookies()
        while True:
            for cookie in cookies:
                if cookie['name'] == 'FGJK':
                   token = cookie['value'] 
                   return token         
                else:
                    cookies = driver.get_cookies()
    
    
    async def get_results(s, endpoint, headers):
        r = await s.get(f'https://www.realestate.com.au/auction-results/{endpoint}', headers=headers)
        #do something with r.html
        print(r, endpoint)
    
    
    async def main():
        token = await get_token()
        s = AsyncHTMLSession()
        headers = {'Cookie': f'FGJK={token}',
                   'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}    
    
        r = await s.get(f'https://sales-events-api.realestate.com.au/sales-events/nsw')
        suburbs = r.json()['data']['suburbResults']
        endpoints = [burb['suburb']['urlValue'] for burb in suburbs]    
        asyncio.gather(*(get_results(s, endpoint, headers) for endpoint in endpoints))
    
    
    asyncio.run(main()) 
    

    【讨论】:

    • 你是怎么找到sales-events-api的?
    • 我在本地机器上运行您的代码,并从 while 循环中打印 cookies。 cookie 中没有FGJK。多次driver.get_cookies()之后,你怎么能抢到FGJK
    • 其实此时sale-events-api没有保护。
    • 如果你能弄清楚他们的 API,那绝对比使用 Selenium 来获取 cookie 更可取。我在加拿大,所以我不完全确定 FGJK 是否只是我的目标,但在 Firefox、Chrome 和 Explorer 中测试它时,我得到了相同的 cookie,每个请求中都必须发送。
    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多