使用请求登录网站

时间:2016-12-14 16:40:51

标签: python python-3.x beautifulsoup python-requests mechanicalsoup

我尝试了两种完全不同的方法。但是我仍然无法获得仅在登录后出现的数据。

我尝试过使用请求,但xpath返回null     导入请求     来自lxml import html

USERNAME = "xxx"
PASSWORD = "xxx"

LOGIN_URL = "http://www.reginaandrew.com/customer/account/loginPost/referer/aHR0cDovL3d3dy5yZWdpbmFhbmRyZXcuY29tLz9fX19TSUQ9VQ,,/"
URL = "http://www.reginaandrew.com/gold-leaf-glass-top-table"


def main():
FormKeyTxt = ""
session_requests = requests.session()

# Get login csrf token
result = session_requests.get(LOGIN_URL)
tree = html.fromstring(result.text)
# Create payload
formKey = str((tree.xpath("//*[ @ id = 'login-form'] / input / @ value")))
FormKeyTxt = "".join(formKey)
#print(FormKeyTxt.replace("['","").replace("']",""))

payload = {
    "login[username]": USERNAME,
    "login[password]": PASSWORD,
    "form_key": FormKeyTxt,
    "persistent_remember_me": "checked"

}

# Perform login
result = session_requests.post(LOGIN_URL, data=payload)

# Scrape url
result = session_requests.get(URL, data=payload)
tree = html.fromstring(result.content)
bucket_names = tree.xpath("//span[contains(@class, 'in-stock')]/text()")
print(bucket_names)
print(result)
print(result.status_code)


if __name__ == '__main__':
main()

我尝试了另一个使用机械汤,但它仍然返回一个空

import argparse
import mechanicalsoup
import urllib.request
from bs4 import BeautifulSoup

parser = argparse.ArgumentParser(description='Login to GitHub.')
parser.add_argument("username")
parser.add_argument("password")
args = parser.parse_args()

browser = mechanicalsoup.Browser()

login_page = browser.get("http://www.reginaandrew.com/gold-leaf-glass-top-table")
login_form = login_page.soup.select("#login-form")[0]


login_form.input({"login[username]": args.username, "login[password]": args.password})


page2 = browser.submit(login_form,login_page.url )
messages = page2.soup.find(class_='in-stock1')
if messages:
    print(messages.text)

print(page2.soup.title.text)

我更了解顶级解决方案,所以我很喜欢使用它,但有什么我想念的吗? (我确定我错过了很多)

1 个答案:

答案 0 :(得分:1)

这应该这样做

import requests
import re

url = "http://www.reginaandrew.com/"
r = requests.session()
rs = r.get(url)
cut = re.search(r'<form.+?id="login-form".+?<\/form>', rs.text, re.S|re.I).group()
action = re.search(r'action="(.+?)"', cut).group(1)
form_key = re.search(r'name="form_key".+?value="(.+?)"', cut).group(1)
payload = {
    "login[username]": "fugees",
    "login[password]": "nugees",
    "form_key": form_key,
    "persistent_remember_me": "on"
}
rs = r.post(action, data=payload, headers={'Referer':url})