python - 美丽的汤没有加载整个页面
问题描述
我得到了这个项目,我在 Trulia.com 上抓取数据,并且我想获取特定位置的最大页面数(最后一个数字)(下图),这样我就可以遍历它并获取所有 href。
为了得到最后一个数字,我的代码按计划运行并且应该返回一个整数,但它并不总是返回相同的数字。我添加了打印(理解列表)以了解问题所在。这是下面的代码和输出。返回被注释,但应该将输出列表的最后一个数字作为 int 返回。
city_link = "https://www.trulia.com/for_rent/San_Francisco,CA/"
def bsoup(url):
resp = r.get(url, headers=req_headers)
soup = bs(resp.content, 'html.parser')
return soup
def max_page(link):
soup = bsoup(link)
page_num = soup.find_all(attrs={"data-testid":"pagination-page-link"})
print([x.get_text() for x in page_num])
# return int(page_num[-1].get_text())
for x in range(10):
max_page(city_link)
我不知道为什么有时它会返回错误的东西。上图是对应的链接。
解决方案
好的,现在如果我了解您想要什么,您正在尝试查看给定位置的出租链接页数。如果我们可以假设给定的链接是唯一需要的链接,那么这段代码:
import requests
import bs4
url = "https://www.trulia.com/for_rent/San_Francisco,CA/"
req = requests.get(url)
soup = bs4.BeautifulSoup(req.content, features='lxml')
def get_number_of_pages(soup):
caption_tag = soup.find('div', class_="Text__TextBase-sc-1cait9d-0-
div Text__TextContainerBase-sc-1cait9d-1 RBSGf")
pagination = caption_tag.text
words = pagination.split(" ")
values = []
for word in words:
if not word.isalpha():
values.append(word)
links_per_page = values[0].split('-')[1]
total_links = values[1].replace(',', '')
no_of_pages = round(int(total_links)/int(links_per_page) + 0.5)
return no_of_pages
for i in range(10):
print(get_number_of_pages(soup))
实现您正在寻找的内容,并且具有可重复性,因为它不与 javascript 交互,而是与页面底部的分页标题交互。
推荐阅读
- android - How to get the SMS date from messenger?
- javascript - Javascript 验证表单不适用于 HTML
- vue.js - 在 Vue CLI 3 中包含“normalize-scss”
- bnf - 为 XML 编写 BNF 语法
- java - 创建一个部分模糊 Theme.Wallpaper 的视图
- html - 从对象数组中打印 One 对象属性并在 angular5 中执行上一个和下一个
- android - Daily job using Evernote's job library
- android - 每当我尝试调用它时,Camera.release() 都无法在代码中工作
- android - How do I change wallpaper periodically using WorkManager?
- c - Warning 'return' with no value, in function returning non-void - What should it return?