【问题标题】:How to scrape a page if it is redirected to another before如果页面之前被重定向到另一个页面,如何抓取页面
【发布时间】:2019-07-30 13:50:35
【问题描述】:

我正在尝试从https://www.memrise.com/course/2021573/french-1-145/garden/speed_review/?source_element=ms_mode&source_screen=eos_ms 中删除一些文本,但是正如您所看到的,当它通过网络驱动程序加载链接时,它会自动将其重定向到登录页面。登录后直接跳转到我要抓取的页面,但是Beautiful Soup一直在抓取登录页面。

如何让 Beautiful Soup 抓取我想要的页面而不是登录页面?

我已经尝试在它刮擦之前输入一个time.sleep() 以便让我有时间登录,但这也没有用。

soup = BeautifulSoup(requests.get("https://www.memrise.com/course/2021573/french-1-145/garden/speed_review/?source_element=ms_mode&source_screen=eos_ms").text, 'html.parser')
while True:
    front_half = soup.find_all(class_='qquestion qtext')
    print(front_half)
    time.sleep(1)

【问题讨论】:

  • 如果它在服务器端处理(我看到它的方式)你不能做任何事情,因为服务器不会提供任何东西。除非您使用 GET 请求发送登录 cookie/..
  • 请你再解释一下,我不明白你的意思

标签: python html web-scraping beautifulsoup


【解决方案1】:

您可能需要的是与requests 的持久会话。 This answer 可能完全满足您的需求。总体思路很简单:

  1. 您打开一个会话并向网站发送请求
  2. 发送登录帖子请求,以便您登录
  3. 查询相同会话的url。

您需要了解登录帖子请求的结构以及传递的数据(用户名、电子邮件等),并使用该数据创建json

import requests

url = 'https://www.memrise.com/course/2021573/french-1-145/garden/speed_review/?source_element=ms_mode&source_screen=eos_ms'

session = requests.session()

login_data = {
    'username': ,
    'csrfmiddlewaretoken': ,
    'password': ,
    'next': '/course/2021573/french-1-145/garden/speed_review/?source_element=ms_mode&source_screen=eos_ms'
}

session.get(url) #this will redirect you and it might load some initial cookies info

r = session.post('https://<theurl>/login.py', login_data)

if r.status_code == 200: #if accepted the request
    res = session.get(url)
    soup = BeautifulSoup(res.text, 'html.parser')
    ## (...) your scraping code

【讨论】:

    【解决方案2】:

    你可以做的是使用硒。只需编写 browser.get("website.you.need") 这将带您进入登录页面。手动登录一次。现在添加一个 for 循环,您需要在同一程序中抓取同一网站的链接,这样浏览器就不会关闭,因此您不会丢失会话。所以直到程序没有结束,你想访问的链接,你都可以。

    您的代码可能如下所示。

    from selenium import webdriver 
    import time 
    
    
    browser = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver") 
    browser.get('abc.com/page=1')
    # this link will redirect you to the login page. Enter your credentials manually. And wait for logging in successfully. 30 seconds would be enough
    time.sleep(30)
    
    links = ["abc.com/page=1","abc.com/page=2"]
    
    for j in range(len(links)):
        link = links[j]
    
        browser.get(link)
        #this wont need login as you are not closing the 
        time.sleep(5)
        html = browser.page_source
        # do your scraping or save the html sourcecode somewhere and scrape it later.
    
    browser.close()
    

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 1970-01-01
      • 2019-11-04
      • 2011-08-22
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 2023-02-02
      • 2015-08-14
      相关资源
      最近更新 更多