You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python数组添加新数据方法及网页爬取URL代码排错

Python数组操作与网页链接爬取问题解答

一、如何在Python中向数组(列表)添加新数据?

Python中常用**列表(list)**实现类似数组的功能,添加元素的常用方法有:

  • 使用append()方法:向列表末尾添加单个元素
    my_list = [1, 2, 3]
    my_list.append(4)
    # 结果: [1, 2, 3, 4]
    
  • 使用extend()方法:向列表末尾批量添加另一个可迭代对象的元素
    my_list = [1, 2, 3]
    my_list.extend([4, 5])
    # 结果: [1, 2, 3, 4, 5]
    
  • 使用insert()方法:在指定索引位置插入元素
    my_list = [1, 2, 3]
    my_list.insert(1, 1.5)
    # 结果: [1, 1.5, 2, 3]
    

二、网页链接爬取代码的问题修正

你的代码存在两处问题,修正后的代码及分析如下:

问题分析

  • 变量名误用:定义的列表变量是urls,循环中错误调用了url.append(),应改为urls.append()
  • 冗余的.text调用:link.get('href')直接返回a标签的href属性字符串值,无需额外调用.text,否则会引发属性错误

修正后的代码

import requests
from bs4 import BeautifulSoup

url = 'https://globalthiel.pl'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'html.parser')

urls = []
for link in soup.find_all('a'):
    href = link.get('href')
    if href:  # 过滤无href属性的a标签
        urls.append(href)
for i in urls:
    print(i)

内容的提问来源于stack exchange,提问作者Thomas Tl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 03:30:51