python - 属性错误 : 'list' object has no attribute 'replace' during change array

标签 python arrays replace beautifulsoup mechanize

我对 Python 没有太多经验,并且在制作网络爬虫时遇到了问题。我正在尝试更改数组中的一个项目,但出现此错误

AttributeError: 'list' object has no attribute 'replace'


import urllib
import mechanize
import requests
import re
from bs4 import BeautifulSoup

def getGoogle(link):
        br = mechanize.Browser()
        br.set_handle_robots(False)
        br.addheaders=[('User-agent','chrome')]

        term = link.replace(" ", "+")
        query = "http://www.google.com/search?q="+term
        htmltext = br.open(query).read()
        soup2 = BeautifulSoup(htmltext, "html.parser")
        search = soup2.findAll('div', attrs={'id':'search'})
        searchtext = str(search[:])
        soup3 = BeautifulSoup(searchtext, "html.parser")
        list_items = soup3.findAll('li', attrs={'class', 'g'})
        for li in list_items:
                for h3 in li.findAll('h3'):
                        for a in h3.findAll('a'):
                                regex = "q(?!.*q).*?amp"
                                pattern = re.compile(regex)
                                source_url = re.findall(pattern, str(a))
                                results_array = [source_url]

                                for result in results_array:
                                        result.append(str(source_url[:].replace("q=","").replace("&amp", "")))

                                        for url in results_array:
                                                r = requests.get(url)

                                                soup = BeautifulSoup(r.content, "html.parser")

                                                g_data = soup.find_all(attrs={"name":"viewport"})

                                                for item in g_data:
                                                        return r.url, 'bevat een viewport'
                                                        break
                                                else:
                                                        return r.url, 'bevat GEEN viewport'

最佳答案

你可以这样做:

result.append(''.join(source_url).replace("q=","").replace("&amp", ""))

关于python - 属性错误 : 'list' object has no attribute 'replace' during change array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33022897/

相关文章:

c# - String.replace "\\"为 "/"

c# - regex.replace 查询字符串参数

arrays - didSelectRowAt 更改所有行中的值

python - 假设一个数组只包含两种元素,如何快速找到它们的边界?

python - Pandas 从日期获取年龄(例如 : date of birth)

python - 使骰子值在 if 语句中不重复

python - 询问长度为 2 的数组列表是否包含给定长度为 1 的数组时出现 ValueError

java - 用4个空格替换java文件中的制表符?

python - matplotlib 出条形图的两个图例

python - 将索引转换为日期时间并获取第 2 列最大值的时间