Python如何更新作为参数传递的链接?

2024-09-30 10:40:45 发布

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

我在一个线程中传递一个链接作为参数,我想在其上添加时间戳。但是在线程所指向的函数中,时间戳值并没有改变,每次我重新扫描它时。如何使timeLink保持动态,并在每次通过while循环时进行更改?代码如下:

def abcStart(timeLink):

    while True:
        res = timeLink
        res.raise_for_status()
        timestamp = BeautifulSoup(res.content, 'html.parser').find_all('b')

        if timestamp[0].text == otherTimestamp[0].text:
            work on something
            break
        if timestamp[0].text > otherTimestamp[0].text:
            continue
        else:
            print('not yet')
        time.sleep(30)
    break

timelink = requests.get('http://example.com/somelink')

threadobj = threading.Thread(target=abcStart, args=(timelink))
threadobj.start()
threadobj.join()

Tags: text参数if链接时间res线程timestamp
2条回答

我想你应该把timeLink请求移到你的函数中:

def abcStart(timeLink):

    while True:
        res = requests.get('http://example.com/somelink')
        res.raise_for_status()
        timestamp = BeautifulSoup(res.content, 'html.parser').find_all('b')

        if timestamp[0].text == otherTimestamp[0].text:
            work on something
            break
        if timestamp[0].text > otherTimestamp[0].text:
            continue
        else:
            print('not yet')
        time.sleep(30)
    break

threadobj = threading.Thread(target=abcStart, args=())
threadobj.start()
threadobj.join()

看起来只有一个http请求被发送。在这条线上:

timelink = requests.get('http://example.com/somelink')

函数接收http响应,并在整个运行过程中使用该值。这将导致我们每次都刮同一页。如果我们想为每个循环迭代获取不同的页面,那么每次都需要执行另一个http请求。像这样:

def abcStart(timeLink):

while True:
    res = requests.get(timeLink) # send request here
    res.raise_for_status()
    timestamp = BeautifulSoup(res.content, 'html.parser').find_all('b')

    if timestamp[0].text == otherTimestamp[0].text:
        work on something
        break
    if timestamp[0].text > otherTimestamp[0].text:
         continue
    else:
        print('not yet')
    time.sleep(30)
break

timeLink = 'http://example.com/somelink' # declare url

threadobj = threading.Thread(target=abcStart, args=(timelink))
threadobj.start()
threadobj.join()

相关问题 更多 >

    热门问题