【问题标题】:Trying to scrape multiple pages sequentially using loop to change url尝试使用循环顺序抓取多个页面以更改 url
【发布时间】:2019-08-26 17:02:41
【问题描述】:

首先,抱歉...我确信这是一个常见问题,但我搜索了一段时间,但在任何地方都没有找到解决方案。

我正在尝试通过从 classicdb 中抓取数据来创建列表。我遇到的两个问题是。

  1. 在 try 循环中编写的抓取在 for 循环内不起作用,但它本身就起作用。目前它只返回 0,即使应该返回值。

  2. 我从 try 循环获得的输出会生成新列表,但我只想获取该值并稍后附加它。

我已经在 for 循环之外尝试了 try 函数,它在那里工作。 我还看到了一些使用了 while true 但对我不起作用的解决方案。

from lxml.html import fromstring
import requests

import traceback
import time
from bs4 import BeautifulSoup as bs

Item_name=[]
Sell_Copper=[]


items= [47, 48]
url = 'https://classic.wowhead.com/item='
fails=[]


for i in items:

        time.sleep(5)
        url1=(url+str(i))
        session = requests.session()
        response = session.get(url1)
        soup = bs(response.content, 'lxml')
        name=soup.select_one('h1').text
        print(name)

        #get the buy prices
        try:
            copper = soup.select_one('li:contains("Sells for") .moneycopper').text
        except Exception as e:
            copper=str(0)

预期的结果是我得到一个黄金值和一个 P_Gold 列表。在这种情况下: 铜='1' Sell_copper=['1','1']

【问题讨论】:

    标签: python-3.x for-loop web-scraping


    【解决方案1】:

    你不需要睡觉。它需要是 div:contains 并且搜索文本需要更改

    import requests
    from bs4 import BeautifulSoup as bs
    
    Item_name=[]
    Sell_Copper=[]
    items= [47, 48]
    url = 'https://classic.wowhead.com/item='
    fails=[]
    
    with requests.Session() as s:
        for i in items:
            response = s.get(url + str(i))
            soup = bs(response.content, 'lxml')
            name = soup.select_one('h1').text
            print(name)
    
            try:
                copper = soup.select_one('div:contains("Sell Price") .moneycopper').text
            except Exception as e:
                copper=str(0)
            print(copper)
    

    【讨论】:

    • 你试过了吗?
    猜你喜欢
    • 2017-07-10
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多