【问题标题】:How do I loop into my Web scraper better?如何更好地循环进入我的网络爬虫?
【发布时间】:2020-05-27 17:56:26
【问题描述】:

我正在尝试通过使刮刀刮取页面上每个项目的链接来刮取网站搜索页面,然后再次解析刮取的链接并从该链接中刮取某些信息。我遇到的问题是,如果初始链接已被抓取,我想遍历每个链接并从中抓取数据,但它目前只抓取链接列表中的第一个值。我想问题出在我的 for 循环上。

这是我当前的代码。

productLinks = []
carMake = [] 


url = "https://buy.cars45.com/cars"
headers = {"Accept-Language": "en-US, en;q=0.5"}


searchResults = requests.get(url, headers=headers)
soup = BeautifulSoup(searchResults.text, "html.parser")

searchlinks = soup.find_all('div', class_='product_box')

for i in searchlinks:
    a = i.find('a').get('href')
    if a:
        productLinks.append(a)
#         print(a)
    else:
        productLinks.append('kNone')


for j in productLinks:
    productPage = requests.get(j, headers=headers)
     soup2 = BeautifulSoup(productPage.text, "html.parser")

     details = soup2.find_all('span', class_='float-right')

     make = details[0].text
     carName.append(make)

但它只是返回重复多次的第一辆车作为输出。

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    如果我理解正确,这应该可以工作

    import requests
    from bs4 import BeautifulSoup
    url ='https://www.lbbusinessjournal.com/'
    
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'html.parser')
    
    links = []
    
    for post in soup.find_all(['h3', 'li'], class_=['entry-title td-module-title', 'menu-item']):
      link = post.find('a')
      if link:
          link = link.get('href')
          links.append(link)
          print(len(link))
          print(link)
    
    for i in links:
      r2 = requests.get(i)
      soup1 = BeautifulSoup(r2.text, 'html.parser')
    
      for post1 in soup1.find_all('h3', class_='entry-title td-module-title'):
          link1 = post1.find('a')
          if link1: 
              print(link1.text)
    

    当我运行你的代码时,它给出了一些错误,所以如果这是你的问题, 您应该检查post1.find('a') 是否返回None。如果post1 不包含<a> 标记,就会发生这种情况。

    【讨论】:

    • @user8173388 再次调用i.find('a').get('href'),尽管i.find('a') 可以默认为None,而a 不包含在您正在解析的html 代码中。由于None 没有名为get 的属性,这将再次导致异常。你能具体解释一下我发布的上述代码对你不起作用吗?
    猜你喜欢
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2012-01-14
    相关资源
    最近更新 更多