[英]Python web scrape with Beautiful Soup
我可以毫無問題地刮擦此站點表; 但是,要訪問我自定義的表,我需要先登錄然后抓取,因為如果沒有,我將獲得默認輸出。 我覺得我已經接近了,但是我對python還是比較陌生的。 期待更多地了解機械化和BeautifulSoup。
如果我故意在下面輸入錯誤的密碼,我會收到“錯誤的密碼”錯誤,這似乎可以正確登錄,但是如何將登錄名連接到要抓取的網址?
from bs4 import BeautifulSoup
import urllib
import csv
import mechanize
import cookielib
cj = cookielib.CookieJar()
br = mechanize.Browser()
br.set_cookiejar(cj)
br.open("http://www.barchart.com/login.php")
br.select_form(nr=0)
br.form['email'] = 'username'
br.form['password'] = 'password'
br.submit()
#print br.response().read()
r = urllib.urlopen("http://www.barchart.com/stocks/sp500.php?view=49530&_dtp1=0").read()
soup = BeautifulSoup(r, "html.parser")
tables = soup.find("table", attrs={"class" : "datatable ajax"})
headers = [header.text for header in tables.find_all('th')]
rows = []
for row in tables.find_all('tr'):
rows.append([val.text.encode('utf8') for val in row.find_all('td')])
with open('snp.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(row for row in rows if row)
#from pymongo import MongoClient
#import datetime
#client = MongoClient('localhost', 27017)
print soup.table.get_text()
我不確定您實際上是否需要登錄才能檢索到問題中的URL。 無論是否登錄,我都會得到相同的結果。
但是,如果確實需要登錄才能訪問其他數據,則問題將是您使用mechanize
登錄,然后使用urllib.urlopen()
訪問該頁面。 兩者之間沒有任何聯系,因此, mechanize
收集的任何會話數據在發出請求時都無法用於urlopen
。
在這種情況下,您無需使用urlopen()
因為您可以打開URL並使用mechanize
訪問HTML:
r = br.open("http://www.barchart.com/stocks/sp500.php?view=49530&_dtp1=0")
soup = BeautifulSoup(r.read(), "html.parser")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.