如何使用python同时从多个页面中提取数据?

2024-06-27 21:08:46 发布

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

我使用Python3.6,我尝试从页面中提取数据,但我希望同时从多个页面中提取数据,代码如下:

   page = requests.get('http://www.poetsgate.com/ViewPoem.aspx?id=12343')
   tree = html.fromstring(page.content)
   text1 = tree.xpath('//div[@class="col1 first"]/text()')
   text2 = tree.xpath('//div[@class="col2 second"]/text()')

有没有任何方法来提取数据,但我不喜欢使用所有网页的网址列表!你知道吗


Tags: 数据代码textdivcomtreehttpget
1条回答
网友
1楼 · 发布于 2024-06-27 21:08:46

如果没有更多的细节,我假设不使用url列表是不可能的(不管你是手工制作,还是通过编程获得它们都是另一个问题;)。你知道吗

我建议使用helper function来使用列表composable

url_list = ["http://example.com/route/page", ...]
for url in url_list:
    output = extract_data(url)
    do_something(output)

def extract_data(url):
   page = requests.get(url)
   tree = html.fromstring(page.content)
   text1 = tree.xpath('//div[@class="col1 first"]/text()')
   text2 = tree.xpath('//div[@class="col2 second"]/text()')
   return text1, text2

相关问题 更多 >