[英]BeautifulSoup, difference between soup() and soup.findAll()?
[英]python BeautifulSoup soup.findAll(), how to make search result match
我最近學習了BeautifulSoup,作為練習,我想使用BeautifulSoup從工作發布中讀取和提取公司和位置信息。我的代碼是:
import urllib
from BeautifulSoup import *
url="http://www.indeed.com/jobs?q=hadoop&start=50"
html=urllib.urlopen(url).read()
soup=BeautifulSoup(html)
company=soup.findAll("span",{"class":"company"})
location=soup.findAll("span",{"class":"location"})
# for c in company:
# print c.text
# print
# for l in location:
# print l.text
print len(company)
print len(location)
我發現公司的長度和位置不一樣。 所以我不知道哪一對(公司,地點)不完整。 我怎樣才能讓它們匹配?
您需要遍歷搜索結果塊並獲取每個塊的公司位置對 :
for result in soup.find_all("div", {"class": "result"}): # or soup.select("div.result")
company = result.find("span", {"class": "company"}).get_text(strip=True)
location = result.find("span", {"class": "location"}).get_text(strip=True)
print(company, location)
您還應該切換到BeautifulSoup4
,您使用的版本已經很老了:
pip install beautifulsoup4
並替換:
from BeautifulSoup import *
有:
from bs4 import BeautifulSoup
上面的代碼打印:
(u'PsiNapse', u'San Mateo, CA')
(u'Videology', u'Baltimore, MD')
(u'Charles Schwab', u'Lone Tree, CO')
(u'Cognizant', u'Dover, NH')
...
(u'Concur', u'Bellevue, WA')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.