在数据帧 python 中对函数结果进行分组

我有我在谷歌新闻中搜索的请求列表


输出在一个列表中给我所有与此新闻的链接


rqsts_catdogtiger = ['Cat' , 'Dog', 'Tiger']


headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}

page=0 #first page of google news (10 first news)

url_list = []

for term in rqsts_catdogtiger[0:3]:      

    url = 'https://www.google.com/search?q={}&tbm=nws&start={}'.format(term,page) #url of request

    print(url)

    url_list.append(url)       


soups = []


for link in url_list:

    response = requests.get(link, headers=headers,verify=False)

    soup = BeautifulSoup(response.text, 'html.parser')

    soups.append(soup)


def find_links():

    for soup in soups:

        results = soup.findAll("div", {'class': 'g'}) #class of google news

        for result in results:

            result_link = result.find('a').get('href') #getting links

            yield result_link


list_of_links = list(find_links())


list_of_links

输出看起来像30个链接的列表:10个,10个,10个CatDogTiger


我如何将此结果组合成这样:pd.DataFrame


    Request Name                   Links

0            Cat      'https://www.polygon.com/2020/3/19/21187025/cats-2019-tom-hooper-mr-mistoffelees-broadway-musical',...

1            Dog      'https://nypost.com/2020/03/19/second-dog-in-hong-kong-tests-positive-for-coronavirus/',...

2          Tiger      'https://tvrain.ru/teleshow/doma_pogovorim/tiger_cave-504935/',...


翻过高山走不出你
浏览 133回答 1
1回答

潇湘沐

如果我理解你很好,你应该首先通过将列表拆分为均匀长的子列表来准备你的数据:list_of_linksimport pandas as pdrqsts_catdogtiger = ['Cat' , 'Dog', 'Tiger']list_of_links = [...] # your list of linksn = int(len(list_of_links) / len(rqsts_catdogtiger))list_of_list_of_links = [list_of_links[i:i + n] for i in range(0, len(list_of_links), n)]之后,您可以轻松地制作.如果希望列表位于列中,请使用以下代码:pandas.DataFrameLinks>>> df = pd.DataFrame({'Request Name': rqsts_catdogtiger, 'Links': list_of_list_of_links})>>> print(df)  Request Name                                              Links0          Cat  [https://www.polygon.com/2020/3/19/21187025/ca...1          Dog  [https://nypost.com/2020/03/19/second-dog-in-h...2        Tiger  [https://tvrain.ru/teleshow/doma_pogovorim/tig...如果要在一个长字符串中包含链接,其中每个链接都用逗号分隔,请使用以下代码:>>> df = pd.DataFrame({'Request Name': rqsts_catdogtiger, 'Links': [', '.join([url for url in l_of_urls]) for l_of_urls in list_of_list_of_links]})>>> print(df)  Request Name                                              Links0          Cat  https://www.polygon.com/2020/3/19/21187025/cat...1          Dog  https://nypost.com/2020/03/19/second-dog-in-ho...2        Tiger  https://tvrain.ru/teleshow/doma_pogovorim/tige...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python