python - 循环浏览网页
问题描述
我正在运行一个脚本,通过从网站上抓取来更新产品价格。该脚本应抓取给定页面的所有名称和价格,然后转到下一页。但是,由于某种原因,它没有继续前进到下一页,而是继续循环浏览同一页。我尝试了许多代码变体,但它仍然不断发生。
这是我的代码:
page_B = 1
url_B = 'https://website/section/food-drink?page=1/' # Initial url
while page_B < 15:
req = Request(url_B, headers={'User-Agent': 'Chrome'})
web_page = urlopen(req).read()
soup = BeautifulSoup(web_page, "html.parser")
for product in soup.find_all('div', class_="product-wrapper"):
# Get product name
product_title = product.find('p', class_='h4 product__title').text
# Get product price
product_price = product.find('p', class_='product__price')
raw_data = list(product_price.children)[-1]
# Remove spaces, newlines and quotes from prices
clean_price = raw_data.strip(' \n"')
print(product_title)
print(clean_price)
csv_writer.writerow([product_title, product_price])
url_base = url_B.split(str(page_B))
page_B += 1
new_url = url_base[0] + str(page_B) + '/'
url_B = new_url
csv_file.close()
代码的最后一部分是我指示脚本更新下一页的 url 的地方。当我运行这个程序时,它会为同一页面打印 15 次产品名称和价格。我怀疑这个问题与局部变量和全局变量有关,但我对编程很陌生,所以还是有点困惑。任何帮助表示赞赏。
解决方案
我已经知道是什么问题了!奇怪的是,网址末尾的最后一个“/”不知何故使地址总是回到第一页,而不管网址中的页码是什么。
所以 'website/section/food-drink?page=1/' 会返回第一页,而 'website/section/food-drink?page=2/' 也会返回第一页,但是 'website/section/food -drink?page=2' 返回第二页。
我一直认为 url 末尾的“/”在很大程度上是多余的,除非后面跟着路径,但事实证明并非如此。
推荐阅读
- api - 限制过快提交的交易
- laravel - 使用电子表格导出具有条件格式的现有模板
- python - Raspberry Pi 4 上的鼠标仿真不起作用
- sql - 将所有外键删除到特定表
- python - 使用 python 和 django 读取输入字段数组
- javascript - 试图了解 e.PreventDefault 和 e.StopPropogation 行为
- azure - 以编程方式需要使用 azure ADB2C 中的手机号码从用户联系信息中更新 MFA 的强身份验证号码
- typescript - TypeScript:通用类实现的包装器
- html - 让一个元素占据几列
- java - 添加一些依赖项后,Android Studio 未显示“立即同步”选项