Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.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
Python 提高XML解析器的速度_Python_Xml_Beautifulsoup - Fatal编程技术网

Python 提高XML解析器的速度

Python 提高XML解析器的速度,python,xml,beautifulsoup,Python,Xml,Beautifulsoup,我目前正在编写一个脚本,使用beautifulsoup解析xml网页。xml文件的一个示例是。该脚本基本上将输出第一个产品URL(来自每个“loc”标记),该URL与已输入的关键字列表相匹配。当前,脚本的控制流如下所示: 将URL传递到一个soup对象并美化它 为每个url标记运行for循环,并将每个loc文本放入列表(清单\ url) 遍历列表,并输出匹配所有关键字的第一个元素,其中“关键字”是输入的关键字列表 for item in inventory_url:

我目前正在编写一个脚本,使用beautifulsoup解析xml网页。xml文件的一个示例是。该脚本基本上将输出第一个产品URL(来自每个“loc”标记),该URL与已输入的关键字列表相匹配。当前,脚本的控制流如下所示:

  • 将URL传递到一个soup对象并美化它
  • 为每个url标记运行for循环,并将每个loc文本放入列表(清单\ url)

  • 遍历列表,并输出匹配所有关键字的第一个元素,其中“关键字”是输入的关键字列表

        for item in inventory_url:
            if all(kw in item for kw in keywords):
                return item
    
我想知道是否有一种方法可以加快解析速度。我已经看过soupstrainer了,但是当我只找到'loc'标签时,它也会接受'image:loc'标签,我不需要这些标签


多谢各位

您尝试过不同的解析器吗

另请参见中的提示:

如果您可以将文件流式传输为简单文本,我认为正则表达式将非常快

import re

pattern = re.compile(r'<url>[\S\s]*?<loc>([\S\s]*?)</loc>[\S\s]*?</url>')

for match in re.finditer(pattern, file.read()):
     #do stuff
重新导入
pattern=re.compile(r'[\S\S]*?([\S\S]*?)[\S\S]*?)
对于re.finditer(模式,file.read())中的匹配:
#做事

[\S\S]*?
是一种懒散的方法,在我们找到下一步之前,它可以按字面意思匹配任何内容。
对于避免中断至关重要

你曾经解析过xml吗?还没有。谢谢你的建议你确定解析是瓶颈吗?如果您是从internet获取网页,我怀疑这比解析网页所需的时间要长1000倍以上。是否使用
re
?可能会更快,而且可能足够强大。。(注意,我不太熟悉webscraping或beautifulsoup,因此我不确定您是否会在转换为文本流以运行正则表达式时遇到速度减慢的问题)
import re

pattern = re.compile(r'<url>[\S\s]*?<loc>([\S\s]*?)</loc>[\S\s]*?</url>')

for match in re.finditer(pattern, file.read()):
     #do stuff