我在这段代码中使用 lxml
模块一次解析多个页面
def read_and_parse_url(url, queue):
""" Read and parse the url """
data = urllib2.urlopen(url).read()
root = lxml.html.fromstring(data)
queue.put(root)
def fetch_parallel(urls_to_load):
""" Read and parse urls in parallel """
result = Queue.Queue()
processes = [multiprocessing.Process(target = read_and_parse_url, args = (url,result)) for url in urls_to_load]
for p in processes:
p.start()
for p in processes:
p.join(15) # 15 seconds timeout
return result
使用队列模块 (result = Queue.Queue()
),在它运行后我检查了 qsize
,大小为零,就像我从未插入过那里的数据(应该是 50+)。
如果我使用 result = multiprocessing.Queue()
创建队列,qsize()
会正确显示大小,但是我遇到了一个新问题:当我使用队列上的 get
方法出现此错误:
Traceback (most recent call last):
File "test.py", line 329, in <module>
d = scrape()
File "test.py", line 172, in scrape
print parsed_urls.get()
File "lxml.etree.pyx", line 1021, in lxml.etree._Element.__repr__ (src/lxml/lxml.etree.c:37950)
File "lxml.etree.pyx", line 863, in lxml.etree._Element.tag.__get__ (src/lxml/lxml.etree.c:36699)
File "apihelpers.pxi", line 15, in lxml.etree._assertValidNode (src/lxml/lxml.etree.c:10557)
AssertionError: invalid Element proxy at 36856848
一些注意事项:
- parsed_urls
只是队列
- 当我使用 threading
模块时,一切正常。唯一的问题是我无法以简单的方式杀死线程,所以我切换到 multiprocessing
模块。
将 Queue
模块与 multiprocessing
模块一起使用有什么问题?好像不行。
有什么线索吗?我几乎搜索了所有这些内容,但找不到任何答案。
最佳答案
Queue.Queue 适用于多线程应用程序:https://docs.python.org/2/library/queue.html不适用于多进程应用。
multiprocessing.Queue 适用于多进程应用程序:https://docs.python.org/2/library/multiprocessing.html#exchanging-objects-between-processes
在这里查看我的完整答案:Python Queue usage works in threading but (apparently) not in multiprocessing
关于python - 并行抓取多个 url 并在队列中插入 lxml 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28490695/