我試圖學習一些基本的網頁刮。我最初設置了scrapy,並注意到它有點令人生畏,所以我決定首先使用beautifulsoup進行單頁抓取練習,然後再進入爬行。我的項目想法是刮掉下面的表格並將信息輸出到excel文件。基本網頁刮美麗的湯:刮表
表位於此頁面上維基百科: http://en.wikipedia.org/wiki/List_of_largest_corporate_profits_and_losses
我得到的輸出是相當成功的!但是,我不確定我的代碼是非常「pythonic」。我有種野蠻人強迫我使用一些正則表達式來獲取數據,我覺得確實有一種更簡單快捷的方式來獲取表格數據並刪除一些討厭的u'Name'格式和圖像鏈接表。在未來,我想知道除了我的黑客方式之外,還有什麼標準方式來刪除表格並刪除格式。
具體而言,在表格的第3列中,我們看到有國旗的圖像以及我關心的信息(國名)。因此,我不能只做細胞[ 3] .find(文本=真)。我周圍這讓通過抓取僅小區3的所有標籤一個,然後使用正則表達式搶僅含標題中的國名:
for j,cell in enumerate(cells):
if j%3 == 0:
text = (cell.findAll('a'))
感謝,併爲長期職位對不起!
from bs4 import BeautifulSoup
import urllib2
import re
wiki = "http://en.wikipedia.org/wiki/List_of_largest_corporate_profits_and_losses"
header = {'User-Agent': 'Mozilla/5.0'} #Needed to prevent 403 error on Wikipedia
req = urllib2.Request(wiki,headers=header)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
table = soup.find("table", { "class" : "wikitable sortable" })
f = open('output.csv', 'w')
num = []; company = []; industry = []; country = []; year = []; reportdate = [];
earnings = []; usdinflation = []; usdrealearnings = []; cunts = [];
for i,row in enumerate(table.findAll("tr")):
cells = row.findAll("td")
if len(cells) == 9:
num.append(cells[0].find(text=True))
company.append(cells[1].findAll(text=True))
industry.append(cells[2].find(text=True))
country.append(cells[3].find(text=True))
year.append(cells[4].find(text=True))
reportdate.append(cells[5].find(text=True))
earnings.append(cells[6].find(text=True))
usdinflation.append(cells[7].find(text=True))
usdrealearnings.append(cells[8].find(text=True))
for j,cell in enumerate(cells):
if j%3 == 0:
text = (cell.findAll('a'))
newstring = re.search(r'(title="\w+\s\w+")|(title="\w+")',str(text))
if not(newstring is None):
newstring2 = re.search(r'("\w+")|("\w+\s\w+")',newstring.group())
cunts.append(newstring2.group())
for i in range(len(num)):
s = str(company[i])
newstring = re.search(r'\w+\s|\w+\w+', s).group();
write_to_file = str(num[i])+ "," + newstring + "," + str(industry[i]) + "," + cunts[i].encode('utf-8') + ","+ str(year[i]) + ","+ str(reportdate[i])+ ","+ earnings[i].encode('utf-8') + "," + str(usdinflation[i]) + "," + str(usdrealearnings[i]) + "\n";
f.write(write_to_file)
f.close()
是的,你可以做一些改變來清理它。對於初學者,一旦你定義了「table」,你就可以使用print table.prettify()打印出這些數據來查看錶節點的子父母關係,這使得在編碼每一步時知道要導航到什麼時更容易。我會很快發佈一個完整的答案,並提供一些建議。 – Amazingred