【问题标题】:Beautiful Soup: not grabbing correct information美丽的汤:没有抓住正确的信息
【发布时间】:2015-12-10 23:52:49
【问题描述】:

我正在用美汤刮粗花名及其对应图片链接:http://www.all-my-favourite-flower-names.com/list-of-flower-names.html

我不仅要对以“A”开头的花朵执行此操作,还希望 scraper 对您可以尝试获取的所有其他花朵(以“B”开头的花朵, “C”、“D”等)。

我能够为一些“A”花拼凑出一些东西......

for flower in soup.find_all('b'):  #Finds flower names and appends them to the flowers list
        flower = flower.string
        if (flower != None and flower[0] == "A"):
            flowers.append(flower.strip('.()'))
        
    for link in soup.find_all('img'):  #Finds 'src' in <img> tag and appends 'src' to the links list
        links.append(link['src'].strip('https://'))

    for stragler in soup.find_all('a'):  #Finds the only flower name that doesn't follow the pattern of the other names and inserts it into flowers list
        floss = stragler.string
        if floss != None and floss == "Ageratum houstonianum.":
            flowers.insert(3, floss)

这个明显的问题是,当任何事情发生变化时,它肯定会崩溃。有人可以帮帮我吗?

【问题讨论】:

  • 考虑使用 PyQuery 代替 BFS,开发时间快得离谱。我在网络浏览器中加载页面。使用 jQuery 语法构造要拾取的元素。只需将“相同”语法粘贴到 Python 的 PyQuery.. Boom.. 中,值就变成了变量。此外,还有一些方法可以通过将鼠标悬停在元素上并复制 jQuery 路径而无需修改即可获取 jQuery 语法。

标签: python django beautifulsoup


【解决方案1】:

问题似乎是花朵已跨页分页。 像这样的东西应该可以帮助您循环浏览不同的页面。 代码未测试

import urllib2
test = {'A':'', 'B':'-B', 'XYZ': '-X-Y-Z'}
flower_list = []
for key, value in test.items():
     page = urllib2.urlopen('http://www.all-my-favourite-flower-names.com/list-of-flower-names{0}.html'.format(
value)).read()
     soup = BeautifulSoup(page)
     # Now do your logic or every page, and probably save the flower names in a list.

【讨论】:

  • 谢谢!这真的很有帮助!
猜你喜欢
  • 2021-08-13
  • 2017-03-22
  • 2020-01-19
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
相关资源
最近更新 更多