找不到美丽的风景

2024-03-29 12:13:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在做一个网络绘图。我希望我的代码从我爬网的所有网址抓取文本。函数getLinks()找到要从中获取数据的链接,并将它们放入数组中。该数组当前填充了12个链接,如下所示: 'http://www.computerstore.nl/product/142504/category-100852/wd-green-wd30ezrx-3-tb.html'

这是我的函数代码,它用我从getLinks()获得的url在数组中循环,并从中获取数据。所以我遇到的问题是它有时返回文本6次,有时8次或10次。但不是应该的12倍。在

def getSpecs(): 
    i = 0 
    while (i < len(clinks)):
        r = (requests.get(clinks[i]))
        s = (BeautifulSoup(r.content))
        for item in s.find_all("div", {"class" :"productSpecs roundedcorners"}):
            print item.find('h3')
        i = i + 1 

getLinks()
getSpecs()

我怎么解决这个问题?请帮忙。在

提前谢谢!在


Tags: 函数代码文本网络http绘图链接www
1条回答
网友
1楼 · 发布于 2024-03-29 12:13:37

以下是经过多次修复的改进代码:

  • 使用在整个脚本生命周期中维护的^{}
  • 使用^{}连接URL部分
  • 使用^{}代替find_all()
  • 改进了在页面上找到产品的方式
  • 将基于索引的循环转换为列表项上的pythonic循环

代码:

from urlparse import urljoin

from bs4 import BeautifulSoup
import requests

base_url = 'http://www.computerstore.nl'
curl = ["http://www.computerstore.nl/category/100852/interne-harde-schijven.html?6437=19598"]

session = requests.Session()
for url in curl:
    soup = BeautifulSoup(session.get(url).content)
    links = [urljoin(base_url, item['href']) for item in soup.select("div.product-list a.product-list-item image-link")]

    for link in links:
        soup = BeautifulSoup(session.get(link).content)
        print soup.find('span', itemprop='name').get_text(strip=True)

它抓取每个产品链接,跟踪它并打印出产品标题(12种产品):

^{pr2}$

相关问题 更多 >