python - 使用 python 3 抓取需要登录的网站

标签 python python-3.x web-scraping beautifulsoup mechanicalsoup

只是一个关于一些抓取身份验证的问题。使用BeautifulSoup:

#importing the requests lib  
import requests
from bs4 import BeautifulSoup

#specifying the page
page = requests.get("http://localhost:8080/login?from=%2F")
#parsing through the api
soup = BeautifulSoup(page.content, 'html.parser')
print(soup.prettify())

我认为这里的输出很重要:

 <table>
   <tr>
    <td>
     User:
    </td>
    <td>
     <input autocapitalize="off" autocorrect="off" id="j_username" name="j_username" type="text"/>
    </td>
   </tr>
   <tr>
    <td>
     Password:
    </td>
    <td>
     <input name="j_password" type="password"/>
    </td>
   </tr>
   <tr>
    <td align="right">
     <input id="remember_me" name="remember_me" type="checkbox"/>
    </td>
    <td>
     <label for="remember_me">
      Remember me on this computer
     </label>
    </td>
   </tr>
  </table>

这可以很好地抓取网站,但需要登录。我在这里使用 mechanicalsup 库:

import mechanicalsoup

browser = mechanicalsoup.StatefulBrowser()
browser.open("http://localhost:8080/login?from=%2F")
browser.get_url()
browser.get_current_page()
browser.get_current_page().find_all('form')
browser["j_username"] = "admin"
browser ["j_password"] = "password"
browser.launch_browser()

但是它仍然不允许我登录。

有人使用过 python 3 的抓取工具来抓取具有身份验证的网站吗?

最佳答案

我发现您正在使用请求。登录站点的语法如下:

import requests
page = requests.get("http://localhost:8080/login?from=%2F", auth=
('username', 'password'))

希望这有帮助!您可以在此处阅读有关身份验证的更多信息:http://docs.python-requests.org/en/master/user/authentication/

关于python - 使用 python 3 抓取需要登录的网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47438699/

相关文章:

python - Django 表单不会覆盖以前的条目

python - django-rest-framework-bulk 批量更新查看输出定制

python - 如何使用 python 定义更高阶样条线?

python - 如何使用 Python 从 sqlite 数据库中提取选定的列

python subprocess.Popen() 与消息队列( celery )

python 吸血鬼号

PHP 简单 Dom 解析器空白数组

r - 如何从 ISI Web of Knowledge 检索有关期刊的信息?

python - 网络从表格中抓取某一行

python - 清理 CSV——开始新行