只是一些简单的虚拟问题,我刚刚开始学习 BeautifulSoup 并发现有不同的方法可以做同样的事情,并且所有方法都工作正常..
我很想知道它们之间的区别:
首先:我测试了以下三行具有相同功能的代码,它们成功运行并获得相同的结果。问题是有什么区别?
shipping_price = container.find('li', {'class':'price-ship'}).text.strip()
shipping_price = container.find('li', 'price-ship').text.strip()
shipping_price = container.find('li', class_='price-ship').text.strip()
是否有类似上述三行代码之一来自以前版本并且很快就会失去支持并被弃用的情况?上述代码是否提供额外的功能?或者它们只是相同。
第二:这有点不同,它与 BeautifulSoup 无关:
uClient = urlopen(my_url)
page_html = uClient.read()
uClient.close()
相反:
page_html = requests.get(my_url).text
如果我用前者替换后者,我就会发现。结果之间没有区别。那么,有什么区别呢?难道只是在上面的两个代码中他们使用不同的模块来获取my_url
?还是还有其他区别?
请对这些问题进行一些说明,提前谢谢您。
最佳答案
documentation中有提到:
In older versions of Beautiful Soup, which don’t have the class_ shortcut, you can use the attrs trick mentioned above. Create a dictionary whose value for “class” is the string (or regular expression, or whatever) you want to search for.
这很好地解释了您在问题第一部分中寻找的内容。
关于python - BeautifulSoup,请求 - 以下代码有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976571/