回答
您應該使用urllib2來獲取URL內容,使用BeautifulSoup來解析HTML/XML。
示例 - 檢索來自StackOverflow.com主頁的所有問題:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen("http://stackoverflow.com")
soup = BeautifulSoup(page)
for incident in soup('h3'):
print [i.decode('utf8') for i in incident.contents]
print
此代碼示例改編自BeautifulSoup documentation。
+1因爲你舉了一個很好的例子。 BeautifulSoup踢屁股;) – 2011-04-12 12:58:11
@dasWeezul謝謝!確定它是一個很好的包,但它有嚴重的unicode問題。 – 2011-04-12 12:58:53
請注意,雖然美麗的湯目前無人居住。我認爲'lxml.html'可以解析HTML,但可能會使用不太友好的API。 (我從來沒有使用美麗的湯,我沒有使用'lxml',所以我不確定。) – 2011-04-12 12:59:55
您可以使用內置的urllib或urllib2從網上獲取數據,但解析本身是最重要的部分。我可以建議美妙的BeautifulSoup嗎?它可以處理任何事情。 http://www.crummy.com/software/BeautifulSoup/
該文檔是按照教程構建的。分類: http://www.crummy.com/software/BeautifulSoup/documentation.html
就你而言,你可能需要使用通配符來查看字典中的所有條目。你可以這樣做:
import urllib2
def getArticles(query, start_index, count):
xml = urllib2.urlopen('http://pali.hum.ku.dk/cgi-bin/cpd/pali?' +
'acti=xsea&tsearch=%s&rfield=entr&recf=%d&recc=%d' %
(query, start_index, count))
# TODO:
# parse xml code here (using BeautifulSoup or an xml parser like Python's
# own xml.etree. We should at least have the name and ID for each article.
# article = (article_name, article_id)
return (article_names # a list of parsed names from XML
def getArticleContent(article):
xml = urllib2.urlopen('http://pali.hum.ku.dk/cgi-bin/cpd/pali?' +
'acti=xart&arid=%d&sphra=undefined' % article_id)
# TODO: parse xml
return parsed_article
現在你可以循環的東西。例如,爲了讓所有的文章開始在「ANA」,使用通配符「*全日空」和循環,直到你得到任何結果:,有
query = 'ana*'
article_dict = {}
i = 0
while (true):
new_articles = getArticles(query, i, 100)
if len(new_articles) == 0:
break
i += 100
for article_name, article_id in new_articles:
article_dict[article_name] = getArticleContent(article_id)
一旦這樣做,你會所有內容的字典文章,由名字引用。我省略瞭解析本身,但在這種情況下非常簡單,因爲一切都是XML。您甚至可能不需要使用BeautifulSoup(儘管它仍然方便且易於使用XML)。
雖然有一個警告字: 在嘗試大量丟棄文章之前,您應該檢查網站的使用策略(也可能是robots.txt)。如果你只是爲自己收到一些文章,他們可能不會在意(字典版權所有者,如果它不是公有領域的話,可能會在乎),但是如果你要刮掉整本字典,這將會是一些重用。
+1對於量身定做的答案。 – 2011-04-12 13:23:44
我非常感謝你的善良教導。非常感謝你。 – SAKAMOTO 2011-04-12 13:38:12
- 1. 用Python刮Ajax
- 2. 用Python 3.6刮Duckduckgo
- 3. 用Python刮寫Javascript
- 4. 用Python刮臉Facebook
- 5. 用Python/BS4刮臉
- 6. Python網絡刮
- 7. Python刮表
- 8. Python的CSV刮
- 9. 刮Python的
- 10. Python刮href iinks
- 11. 用Python數組刮取URL
- 12. Wikipedia使用Python刮臉
- 13. 使用BeautifulSoup刮網頁Python
- 14. 使用python刮ajax頁面
- 15. 用Python刮新聞網站
- 16. Python:用js刮網頁
- 17. 使用Python刮* .aspx內容
- 18. 用Python颳去Web數據
- 19. 使用python刮取數據
- 20. 用Python刮臉BeautifulSoup 4
- 21. 如何用Python刮取XML?
- 22. Scrapy Python Craigslist刮刀
- 23. Python 3刮黃頁
- 24. Python Web刮索引
- 25. Python刮板諮詢
- 26. Python數據刮板
- 27. Python鏈接刮板
- 28. 網絡刮python表
- 29. Javascript的Python刮刀?
- 30. 使用Python刮取Web應用程序
謝謝你快速回復。但我是認真的初學者,因此無法理解從不可數的URL獲取包括A到Z定義在內的所有內容的方式。 – SAKAMOTO 2011-04-12 12:58:13
[Scraping html with Python or ...](http://stackoverflow.com/questions/2181708/scraping-html-with-python-or) – 2011-04-12 13:00:33
可以請你細化你的問題,並寫下你到底是什麼試圖在輸入和期望的輸出方面刮擦? – 2011-04-12 13:36:55