这实际上是在使用线程来获取url吗?

2024-09-30 08:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

提前谢谢你的帮助。我是Python的新手,正在尝试如何使用线程模块从NY每日新闻站点获取url。我把下面的内容放在一起,这个脚本正在报废,但是它似乎没有比以前快,所以我不确定线程是否正在进行。如果是的话,你能告诉我吗?我能写些什么让我知道吗?还有其他关于穿线的建议吗?在

谢谢。在

from bs4 import BeautifulSoup, SoupStrainer
import urllib2
import os
import io
import threading

def fetch_url():
    for i in xrange(15500, 6100, -1):
        page = urllib2.urlopen("http://www.nydailynews.com/search-results/search-results-7.113?kw=&tfq=&afq=&page={}&sortOrder=Relevance&selecturl=site&q=the&sfq=&dtfq=seven_years".format(i))
        soup = BeautifulSoup(page.read())
        snippet = soup.find_all('h2')
        for h2 in snippet:
            for link in h2.find_all('a'):
                logfile.write("http://www.nydailynews.com" + link.get('href') + "\n")
        print "finished another url from page {}".format(i)

with open("dailynewsurls.txt", 'a') as logfile:
    threads = threading.Thread(target=fetch_url())
    threads.start()

Tags: infromimporthttpurlforwwwpage
2条回答

下面是一个简单的实现(它将很快将您从纽约新闻网)公司名称:

def fetch_url(i, logfile):
    page = urllib2.urlopen("http://www.nydailynews.com/search-results/search-results-7.113?kw=&tfq=&afq=&page={}&sortOrder=Relevance&selecturl=site&q=the&sfq=&dtfq=seven_years".format(i))
    soup = BeautifulSoup(page.read())
    snippet = soup.find_all('h2')
    for h2 in snippet:
        for link in h2.find_all('a'):
            logfile.write("http://www.nydailynews.com" + link.get('href') + "\n")
    print "finished another url from page {}".format(i)

with open("dailynewsurls.txt", 'a') as logfile:
    threads = []
    for i in xrange(15500, 6100, -1):
        t = threading.Thread(target=fetch_url, args=(i, logfile))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()

请注意,fetch_url将URL中要替换的数字作为参数,并且该参数的每个可能值都在其自己的独立线程中启动。在

我强烈建议将作业分成更小的批次,一次运行一个批次。在

不,你没有使用线程。threads = threading.Thread(target=fetch_url())在主线程中调用fetch_url(),等待它完成并将其返回值(None)传递给threading.Thread构造函数。在

相关问题 更多 >

    热门问题