【问题标题】:How do a loop through a list of URLs, follow each link, and pull content into array如何循环遍历 URL 列表、跟踪每个链接并将内容拉入数组
【发布时间】:2021-10-22 23:18:37
【问题描述】:

我已经从 API 中提取数据,我正在遍历所有内容并找到一个键:具有 URL 的值。所以我正在创建一个单独的 URL 列表,我需要做的是点击链接并从页面中获取内容,将该页面的内容拉回数组/列表(它只是一段文本) 并且当然会遍历剩余的 URL。我是否需要使用 Selenium 或 BS4?如何循环访问并将页面内容拉入我的数组/列表?

json looks like this:

{
"merchandiseData": [
    {
        "clientID": 3003,
        "name": "Yasir Carter",
        "phone": "(758) 564-5345",
        "email": "leo.vivamus@pedenec.net",
        "address": "P.O. Box 881, 2723 Elementum, St.",
        "postalZip": "DX2I 2LD",
        "numberrange": 10,
        "name1": "Harlan Mccarty",
        "constant": ".com",
        "text": "deserunt",
        "url": "https://www.deserunt.com",
        "text": "https://www."
    },
]
}

到目前为止的代码:

import requests
import json
import pandas as pd 
import sqlalchemy as sq
import time
from datetime import datetime, timedelta
from flatten_json import flatten# read file
with open('_files/TestFile2.json', 'r') as f:
    file_contents = json.load(f)
allThis = []
for x in file_contents['merchandiseData']:
    holdAllThis = {
        'client_id' : x['clientID'],
    'client_description_link' : x['url']
    }
    allThis.append(holdAllThis)
    print(client_id, client_description_link)
print(allThis)

【问题讨论】:

  • allThis 列表有客户端 id 和 url 吗?这是示例 json 吗?如果没有,_files/TestFile2.json 中有多少 JSON 数组?您是否只想获取每个 URL 并从 UI 中提取一些文本?
  • 如果 URL 不同,您应该编写不同的代码来抓取每个 URL。是使用 bs4 还是 selenium,这取决于网页 - 如果页面是由 JavaScript 加载的,则使用 selenium,否则 bs4 就可以了。
  • 嗨@cruisepandey。我在此处附加了 json 文件的示例:{github.com/webdevr712/python_follow_links.git} 当上面的脚本运行时,我得到了 clientID 和 url 的列表,是的,文件是 json。然后我想获取该列表,针对它运行一个 python 脚本去抓取每个 url,并将内容拉回一个数组,
  • 嗨@Ram - 不确定我是否跟随。这些网址大约有 10K,所以我不能为每个网址设置单独的代码。脚本需要循环,
  • 从您的 JSON 数据中,我看到 URL 不同。您打算如何抓取所有这些 URL?顺便说一句,你想从这些 URL 中提取什么数据?

标签: json python-3.x selenium beautifulsoup


【解决方案1】:

也许使用https://github.com/webdevr712/python_follow_links 和 pandas 上发布的 JSON:

import pandas as pd
import requests

# function mostly borrowed from https://stackoverflow.com/a/24519419/9192284
def site_response(link):
    try:
        r = requests.get(link, headers=headers)

        # Consider any status other than 2xx an error
        if not r.status_code // 100 == 2:
            return "Error: {}".format(r)

        return r.reason
    except requests.exceptions.RequestException as e:
        # A serious problem happened, like an SSLError or InvalidURL
        return "Error: {}".format(e)

# set headers
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.3"
}

# url for downloading the json file
url = 'https://raw.githubusercontent.com/webdevr712/python_follow_links/main/merchData.json'

# get the json into a dataframe
df = pd.read_json(url)
df = pd.DataFrame(df['merchandiseData'].values.tolist())

# new column to store the response from running the site_response() function for each string in the 'url' column
df['site_response'] = df.apply(lambda x: site_response(x['url']), axis=1)

# print('OK responses:')
# print(df[df['site_response'].str.contains('OK')])

# output
print('\n\nAll responses:')
print(df[['url', 'site_response']])

输出:

All responses:

    url                         site_response
0   https://www.deserunt.com    Error: HTTPSConnectionPool(host='www.deserunt....
1   https://www.aliquip.com     Error: HTTPSConnectionPool(host='www.aliquip.c...
2   https://www.sed.net         Error: <Response [406]>
3   https://www.ad.net          OK
4   https://www.Excepteur.edu   Error: HTTPSConnectionPool(host='www.excepteur...

全帧输出:

  clientID               name           phone  \
0      3003       Yasir Carter  (758) 564-5345   
1      3103  Elaine Mccullough  1-265-168-1287   
2      3203      Vanna Elliott  (113) 485-7272   
3      3303    Adrienne Holden  1-146-431-3745   
4      3403         Freya Vang  (858) 195-4886   

                                       email  \
0                    leo.vivamus@pedenec.net   
1                sodales@enimcondimentum.net   
2                             elit.a@dui.org   
3  lacus.quisque@magnapraesentinterdum.co.uk   
4                  diam.dictum@velmauris.net   

                             address    postalZip  numberrange  \
0  P.O. Box 881, 2723 Elementum, St.     DX2I 2LD           10   
1                      7529 Dui. St.  24768-76452            9   
2           Ap #368-6127 Lacinia Av.         6200            5   
3           Ap #522-3209 Euismod St.        66746            3   
4          P.O. Box 159, 416 Dui Ave       158425            4   

             name1 constant          text                        url  \
0   Harlan Mccarty     .com  https://www.   https://www.deserunt.com   
1  Kaseem Petersen     .com  https://www.    https://www.aliquip.com   
2  Kennan Holloway     .net  https://www.        https://www.sed.net   
3  Octavia Lambert     .net  https://www.         https://www.ad.net   
4    Kitra Maynard     .edu  https://www.  https://www.Excepteur.edu   

                                       site_response  
0  Error: HTTPSConnectionPool(host='www.deserunt....  
1  Error: HTTPSConnectionPool(host='www.aliquip.c...  
2                            Error: <Response [406]>  
3                                                 OK  
4  Error: HTTPSConnectionPool(host='www.excepteur...  

从那里您可以继续抓取返回“OK”的每个站点并使用 Selenium(如果需要 - 您可以使用其他函数检查)或 BS4 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 2017-03-15
    • 2020-10-15
    • 1970-01-01
    • 2023-03-16
    • 2020-02-22
    相关资源
    最近更新 更多