使用python登录网站和Web Scapping

时间:2018-03-29 16:02:16

标签: python web-scraping beautifulsoup

我正在尝试找出网页为我的研究项目取消房地产网站https://www.brickz.my/的方法。我一直在尝试硒和美丽的汤,并决定选择美丽的汤对我来说是最好的方式,因为每个房地产的网址结构允许我的代码轻松,快速地浏览网站

我正在尝试为每个房地产建立一个数据库交易'。如果没有登录,将只显示特定房产的10个最新交易。通过登录,我可以访问特定类型属性的整个事务。这是一个例子

without login, i can only access 10 transaction for each property

After login, i can access to more than 10 transaction plus previously obscure property address

我尝试在python中使用请求登录,但它一直将我带到页面而没有登录并结束,我只是设法废弃10个最新的交易而不是整个交易。这是我在python

中登录代码的示例
import requests
from bs4 import BeautifulSoup
page = requests.get("https://www.brickz.my/login/", auth=
('email', 'password'))

headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; SM-G928X Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.83 Mobile Safari/537.36'}

soup = BeautifulSoup(page.content, 'html.parser')
#I put one of the property url to be scrapped inside response
response = get("https://www.brickz.my/transactions/residential/kuala- 
           lumpur/titiwangsa/titiwangsa-sentral-condo/non-landed/?range=2012+Oct-", 
           headers = headers)

以下是我用来废弃表格的内容

  table = BeautifulSoup(response.text, 'html.parser')
  table_rows = table.find_all('tr')

  names = []   
  for tr in table_rows:
      td = tr.find_all('td')
      row = [i.text for i in td]
      names.append(row)

我如何成功登录并访问整个交易?我听说过Mechanize库,但它不适用于python 3。

如果我的问题不明确,我很抱歉,这是我第一次发帖,而且我只是在几个月前学会使用python。

2 个答案:

答案 0 :(得分:1)

简单的HTTP跟踪将显示对https://www.brickz.my/login/进行POST,emailpw作为表单参数。

转换为此请求命令:

session = requests.Session()
resp = session.post('https://www.brickz.my/login/', data={'email': '<youremail>', 'pw': '<yourpassword'})
if resp.ok:
    print("You should now be logged in")

# then use session to request the site, like 
# resp = session.get("https://www.brickz.my/whatever")

警告:由于我在那里没有帐户,因此未经测试。

答案 1 :(得分:1)

尝试以下代码。打印时看到了什么(更改emailpassword)?它不打印Logout作为结果吗?

import requests
from bs4 import BeautifulSoup

URL = "https://www.brickz.my/login/"

payload = {
'email': 'your_email',
'pw': 'your_password',
'submit': 'Submit'
}

with requests.Session() as s:
    s.headers = {"User-Agent":"Mozilla/5.0"}
    s.post(URL,data=payload)
    res = s.get("https://www.brickz.my/")
    soup = BeautifulSoup(res.text,"lxml")
    for items in soup.select("select#menu_select .nav2"):
        data = [' '.join(item.text.split()) for item in items.select("option")[-1:]]
        print(data)