Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用json或xml格式的python从网页中提取信息?_Python_Json_Xml_Parsing_Web Crawler - Fatal编程技术网

如何使用json或xml格式的python从网页中提取信息?

如何使用json或xml格式的python从网页中提取信息?,python,json,xml,parsing,web-crawler,Python,Json,Xml,Parsing,Web Crawler,我需要帮助从网页中提取信息。我给出了URL,然后我需要提取信息,如联系号码、地址、href、人名等。我能够完全提取带有已知标记的URL的页面源代码。但是我需要一个通用的源代码来从任何URL提取这些数据。我使用regex提取电子邮件,例如 import urllib import re #htmlfile=urllib.urlopen("http://www.plainsboronj.com/content/departmental-directory") urls=["http://www.pl

我需要帮助从网页中提取信息。我给出了URL,然后我需要提取信息,如联系号码、地址、href、人名等。我能够完全提取带有已知标记的URL的页面源代码。但是我需要一个通用的源代码来从任何URL提取这些数据。我使用regex提取电子邮件,例如

import urllib
import re
#htmlfile=urllib.urlopen("http://www.plainsboronj.com/content/departmental-directory")
urls=["http://www.plainsboronj.com/content/departmental-directory"]
i=0
regex='\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b'
pattern=re.compile(regex)
print pattern
while i<len(urls):
    htmlfile=urllib.urlopen(urls[i])
    htmltext=htmlfile.read()
    titles=re.findall(pattern,htmltext)
    print titles
    i+=1
导入urllib
进口稀土
#htmlfile=urllib.urlopen(“http://www.plainsboronj.com/content/departmental-directory")
URL=[”http://www.plainsboronj.com/content/departmental-directory"]
i=0
正则表达式='\b[A-Za-z0-9.\uz%+-]+@[A-Za-z0-9.-]+\[A-Za-z]{2,6}\b'
pattern=re.compile(regex)
印刷图案

而我首先需要修复正则表达式。 \需要在python字符串中转义。 解决此问题的简单方法是使用原始字符串r“”


regex=r'\b[A-Za-z0-9.+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b

同时,经过一些小的修改后,我成功地让它工作了(请注意,我正在使用Python 3.4.2):


祝你好运

我认为你走错了方向:你有一个HTML文件,你试图从中提取信息。您已经开始通过在“@”符号上进行筛选来查找电子邮件地址(因此您可以选择使用正则表达式)。但是其他的东西,比如名字,电话号码。。。使用正则表达式无法识别,因此另一种方法可能有用。在URL“”下,有一些关于如何解析HTML文件的说明。在我看来,这将是解决您需求的更好方法。

您确定正则表达式正确吗?我已经下载了您正在访问的文件,并按照您的表达式进行了筛选,结果因我使用的正则表达式类型而异(我使用了Ultra Edit文本编辑器(Perl和UNIX正则表达式)和Cygwin UNIX emulator)。请注意,正则表达式语法取决于底层技术。在python脚本中运行正则表达式时,它可以正常工作。请给我一些建议来实现我剩下的目标。我甚至将我的正则表达式与一个示例进行了比较,谢谢,它已经在python-2.7中为我工作了。请建议我一些工作的通用方式的名称,电话号码,地址,链接,邮件等。。用于所有其他信息提取和导出为json。我知道我可以运行单独的separte正则表达式,但不是这样。我需要提取所有信息并以xml或json格式存储。短暂性脑缺血发作
import urllib.request
import re
#htmlfile=urllib.urlopen("http://www.plainsboronj.com/content/departmental-directory")
urls=["http://www.plainsboronj.com/content/departmental-directory"]
i=0
regex='[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}'
pattern=re.compile(regex)
print(pattern)
while i<len(urls):
    htmlfile=urllib.request.urlopen(urls[i])
    htmltext=htmlfile.read()
    titles=re.findall(pattern,htmltext.decode())
    print(titles)
    i+=1
['townshipclerk@plainsboronj.com', 'acancro@plainsboronj.com',  ...]