网络爬虫从列表元素中提取 [英] Web crawler to extract from list elements

查看:293
本文介绍了网络爬虫从列表元素中提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从提取物<李方式> 标记的日期,并把它们存储在一个Excel文件

 <立GT; 1991年1月13日:至少40人< A HREF =......> &所述; / A> < /李>

code:

 进口的urllib2
进口OS
从日期时间日期时间进口
进口重
os.environ [郎] =的en_US.UTF-8
从BS4进口BeautifulSoup第1页= urllib2.urlopen(http://en.wikipedia.org/wiki/List_of_human_stampedes)
汤= BeautifulSoup(第1页)
李= soup.find_all(礼)
数= 0
而计数< LEN(李):
   汤= BeautifulSoup(李[计数])
   DATE_STRING,其余部分为soup.li.text.split(':',1)
   打印datetime.strptime(DATE_STRING,'%A%D,%Y')。的strftime(%D /%M /%Y')
   数+ = 1

错误:

 回溯(最后最近一次调用):
  文件C:\\用户\\索尼\\桌面\\垃圾桶\\履带尝试\\ trytest.py,13号线,上述<&模块GT;
    汤= BeautifulSoup(李[计数])
  文件C:\\ Python27 \\ lib目录\\站点包\\ BS4 \\ __ init__.py,线路161,在__init__
    标记= markup.read()
类型错误:'NoneType'对象不是可调用
[完成了4.0s,退出code 1]

我不知道如何写在Excel中提取因而每个文本。没有它包含code。参见问题:网络爬虫列表之间提取


解决方案

现在的问题是 - 有不包含所需要的数据无关标记<。 / p>

更具体。例如,如果你想从20世纪获得事件列表,先找到头,并得到事件的列表,从它的父的的以下 UL 兄弟。此外,并非列表中的每个项目都有在%B%d个日期,%Y 格式 - 你需要通过来处理它尝试/除外块:

 进口的urllib2
从日期时间日期时间进口
从BS4进口BeautifulSoup
第1页= urllib2.urlopen(http://en.wikipedia.org/wiki/List_of_human_stampedes)
汤= BeautifulSoup(第1页)事件= soup.find('跨',ID ='20th_century')。parent.find_next_sibling(UL)
在events.find_all(礼)事件:
    尝试:
        DATE_STRING,其余部分为event.text.split(':',1)
        打印datetime.strptime(DATE_STRING,'%A%D,%Y')。的strftime(%D /%M /%Y')
    除了ValueError错误:
        打印event.text

打印:

  19/09/1902
30/12/1903
1908年11月1日
24/12/1913
23/10/1942
1946年9月3日
1954年在500-800大壶节,阿拉哈巴德杀害。
1956年1月1日
1971年2月1日
1979年3月12日
20/10/1982
29/05/1985
13/03/1988
20/08/1988


更新版本(获得一个世纪下的所有UL组):

 事件= soup.find('跨',ID ='20th_century')。parent.find_next_siblings()
在事件标签:
    如果tag.name ==H2:
        打破
    在tag.find_all(礼)事件:
        尝试:
            DATE_STRING,其余部分为event.text.split(':',1)
            打印datetime.strptime(DATE_STRING,'%A%D,%Y')。的strftime(%D /%M /%Y')
        除了ValueError错误:
            打印event.text

I am trying to extract from <li> tags the dates and store them in an Excel file.

<li>January 13, 1991: At least 40 people <a href ="......."> </a> </li>

Code:

import urllib2
import os 
from datetime import datetime
import re
os.environ["LANG"]="en_US.UTF-8"
from bs4 import BeautifulSoup

page1 = urllib2.urlopen("http://en.wikipedia.org/wiki/List_of_human_stampedes")
soup = BeautifulSoup(page1)
li =soup.find_all("li")
count = 0
while count < len(li):
   soup = BeautifulSoup(li[count])
   date_string, rest = soup.li.text.split(':', 1)
   print datetime.strptime(date_string, '%B %d, %Y').strftime('%d/%m/%Y')
   count+=1

Error:

Traceback (most recent call last):
  File "C:\Users\sony\Desktop\Trash\Crawler Try\trytest.py", line 13, in <module>
    soup =BeautifulSoup(li[count])
  File "C:\Python27\lib\site-packages\bs4\__init__.py", line 161, in __init__
    markup = markup.read()
TypeError: 'NoneType' object is not callable
[Finished in 4.0s with exit code 1]

I don't know how to write each text extracted in excel thus. Haven't included in it the code. Refer question: Web crawler to extract in between the list

解决方案

The problem is - there are irrelevant li tags that don't contain the data you need.

Be more specific. For example, if you want to get the list of events from the "20th century", first find the header and get the list of events from it's parent's following ul sibling. Also, not every item in the list has the date in the %B %d, %Y format - you need to handle it via try/except block:

import urllib2
from datetime import datetime
from bs4 import BeautifulSoup


page1 = urllib2.urlopen("http://en.wikipedia.org/wiki/List_of_human_stampedes")
soup = BeautifulSoup(page1)

events = soup.find('span', id='20th_century').parent.find_next_sibling('ul')
for event in events.find_all('li'):
    try:
        date_string, rest = event.text.split(':', 1)
        print datetime.strptime(date_string, '%B %d, %Y').strftime('%d/%m/%Y')
    except ValueError:
        print event.text

Prints:

19/09/1902
30/12/1903
11/01/1908
24/12/1913
23/10/1942
09/03/1946
1954 500-800 killed at Kumbha Mela, Allahabad.
01/01/1956
02/01/1971
03/12/1979
20/10/1982
29/05/1985
13/03/1988
20/08/1988


Updated version (getting all ul groups under a century):

events = soup.find('span', id='20th_century').parent.find_next_siblings()
for tag in events:
    if tag.name == 'h2':
        break
    for event in tag.find_all('li'):
        try:
            date_string, rest = event.text.split(':', 1)
            print datetime.strptime(date_string, '%B %d, %Y').strftime('%d/%m/%Y')
        except ValueError:
            print event.text

这篇关于网络爬虫从列表元素中提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆