我正在做一个学校项目,目标是用自然语言工具包分析诈骗邮件。基本上,我愿意做的是比较不同年份的骗局,试图找到一个趋势——它们的结构是如何随着时间而改变的。
我找到了一个诈骗数据库:http://www.419scam.org/emails/
我想用python下载链接的内容,但是我卡住了。
我的代码:
from BeautifulSoup import BeautifulSoup
import urllib2, re
html = urllib2.urlopen('http://www.419scam.org/emails/').read()
soup = BeautifulSoup(html)
links = soup.findAll('a')
links2 = soup.findAll(href=re.compile("index"))
print links2
所以我可以获取链接,但我还不知道如何下载内容。有什么想法吗?谢谢!
最佳答案
您已经有了一个好的开始,但是现在您只需检索索引页并将其加载到BeautifulSoup解析器中。现在已经有了链接中的ref,您基本上需要打开所有这些链接,并将其内容加载到数据结构中,然后可以使用这些数据结构进行分析。
这实际上相当于一个非常简单的网络爬虫。如果你能使用其他人的代码,你可以通过谷歌“python Web crawler”找到一些合适的东西。我已经看过其中的一些,它们足够简单,但是对于这个任务来说可能是过度的。大多数网络爬虫使用递归遍历给定站点的完整树。看起来简单得多的东西就足够了。
考虑到我对BeautifulGroup的不熟悉,这个基本结构将有望让您走上正确的道路,或者让您了解web爬行是如何完成的:
from BeautifulSoup import BeautifulSoup
import urllib2, re
emailContents = []
def analyze_emails():
# this function and any sub-routines would analyze the emails after they are loaded into a data structure, e.g. emailContents
def parse_email_page(link):
print "opening " + link
# open, soup, and parse the page.
#Looks like the email itself is in a "blockquote" tag so that may be the starting place.
#From there you'll need to create arrays and/or dictionaries of the emails' contents to do your analysis on, e.g. emailContents
def parse_list_page(link):
print "opening " + link
html = urllib2.urlopen(link).read()
soup = BeatifulSoup(html)
email_page_links = # add your own code here to filter the list page soup to get all the relevant links to actual email pages
for link in email_page_links:
parseEmailPage(link['href'])
def main():
html = urllib2.urlopen('http://www.419scam.org/emails/').read()
soup = BeautifulSoup(html)
links = soup.findAll(href=re.compile("20")) # I use '20' to filter links since all the relevant links seem to have 20XX year in them. Seemed to work
for link in links:
parse_list_page(link['href'])
analyze_emails()
if __name__ == "__main__":
main()
关于python - 从Python中的URL下载文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10936177/