Skip to main content
 首页 » 编程设计

python之为什么我在不使用 strip() 时会收到与 strip() 相关的错误 (Python)

2025年05月04日29落叶无声

我正在使用 BeautifulSoup 在 Python 中完成抓取任务,但遇到了一些奇怪的错误。它提到了 strip,我没有使用它,但我猜可能与 BSoup 的进程有关?

在我试图转到原始 url 的任务中,找到第 18 个链接,单击该链接 7 次,然后在第 7 页返回第 18 个链接的名称结果。我正在尝试使用一个函数从第 18 个链接获取 href,然后调整全局变量以每次使用不同的 url 进行递归。关于我所缺少的任何建议都会非常有帮助。我将列出代码和错误:

from bs4 import BeautifulSoup 
import urllib 
import re 
 
nameList = [] 
urlToUse = "http://python-data.dr-chuck.net/known_by_Basile.html" 
 
def linkOpen(): 
    global urlToUse 
    html = urllib.urlopen(urlToUse) 
    soup = BeautifulSoup(html, "lxml") 
    tags = soup("li") 
    count = 0 
    for tag in tags: 
        if count == 17: 
            tagUrl = re.findall('href="([^ ]+)"', str(tag)) 
            nameList.append(tagUrl) 
            urlToUse = tagUrl 
            count = count + 1 
        else: 
            count = count + 1 
            continue 
 
bigCount = 0 
while bigCount < 9: 
    linkOpen() 
    bigCount = bigCount + 1 
 
print nameList[8] 

错误:

Traceback (most recent call last): 
  File "assignmentLinkScrape.py", line 26, in <module> 
    linkOpen() 
  File "assignmentLinkScrape.py", line 10, in linkOpen 
    html = urllib.urlopen(urlToUse) 
  File          
 
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 87, in urlopen 
    return opener.open(url)   File  
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 185, in open 
    fullurl = unwrap(toBytes(fullurl))   File 
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1075, in unwrap 
        url = url.strip() AttributeError: 'list' object has no attribute 'strip' 

请您参考如下方法:

re.findall() 返回匹配列表。 urlToUse 是一个列表,您正试图将它传递给 urlopen(),它需要一个 URL 字符串。