import requests import re url = 'https://jn.lianjia.com/zufang/pg1/#contentList' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299' } # 获取总页数 response = requests.get(url, headers=headers) html = response.text total_page = re.search(r'data-totalpage="(\d+)"', html).group(1) print(total_page)将total_page变成int型
时间: 2024-04-01 22:35:05 浏览: 20
你可以使用 `int()` 函数将字符串类型的 `total_page` 转换成整数类型。
以下是修改后的示例代码:
```python
import requests
import re
url = 'https://jn.lianjia.com/zufang/pg1/#contentList'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'
}
# 获取总页数
response = requests.get(url, headers=headers)
html = response.text
total_page = int(re.search(r'data-totalpage="(\d+)"', html).group(1))
print(total_page)
```
这个示例代码可以获取济南市链家网租房信息的总页数,并将其转换成整数类型。你可以根据自己的需要修改代码,提取其他信息。
相关问题
获取总页数 url1 = https://jn.lianjia.com/zufang/pg1/#contentList response = requests.get(url1, headers=header) html = response.text match = re.search(r data-totalpage=(\d+) , html) if match: total_p
age = int(match.group(1)),这是一个获取链家网租房信息总页数的 Python 代码段。具体来说,使用 requests 库发送 GET 请求获取链家网租房首页(pg1)的 HTML 内容,然后使用正则表达式从 HTML 内容中匹配 data-totalpage 属性的值,即租房信息的总页数,并将其转换为整数类型赋值给变量 total_page。注意,这里使用了伪装头(headers)来模拟浏览器访问,以避免被反爬虫机制拦截。
url1 = 'https://jn.lianjia.com/zufang/pg1/#contentList' response = requests.get(url1, headers=header) html = response.text match = re.search(r'data-totalpage="(\d+)"', html) if match: total_page = int(match.group(1)) else: print('未匹配到结果')for num in range(1, total_page + 1):中没找到total_page
你需要将获取总页数的代码放在循环之前,确保能够成功获取总页数,然后再进行循环。
以下是一个示例代码:
```python
import requests
import re
url = 'https://jn.lianjia.com/zufang/pg1/#contentList'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'
}
# 获取总页数
response = requests.get(url, headers=headers)
html = response.text
match = re.search(r'data-totalpage="(\d+)"', html)
if match:
total_page = int(match.group(1))
print(total_page)
else:
print('未匹配到结果')
# 循环获取每一页数据
for num in range(1, total_page + 1):
url = f'https://jn.lianjia.com/zufang/pg{num}/#contentList'
response = requests.get(url, headers=headers)
html = response.text
# 提取数据的代码
# ...
```
这个示例代码先获取总页数,然后再进行循环,获取每一页的数据。你需要根据自己的需求,修改提取数据的代码。