在Python爬虫中拼接网址通常有以下几种方法:
1. 使用`urllib.parse.urljoin`函数:
from urllib.parse import urljoin
base_url = 'https://www.example.com'
relative_path = '/path/to/page'
full_url = urljoin(base_url, relative_path)
2. 使用`urllib.parse.urlencode`函数:
from urllib.parse import urlencode
base_url = 'https://www.example.com'
params = {
'sortField': '人工智能',
'pageIndex': 3,
'pageSize': 20
}
full_url = f'{base_url}?{urlencode(params)}'
3. 使用`str.format`方法:
base_url = 'https://www.example.com/item/{}'
ids = [, ]
for id in ids:
url = base_url.format(id)
4. 使用f-string(Python 3.6+):
base_url = 'https://www.example.com/item/{}'
ids = [, ]
for id in ids:
url = f'{base_url.format(id)}'
5. 使用`requests`库的`Request`对象(如果使用Scrapy框架):
from scrapy.http import Request
base_url = 'https://www.example.com'
relative_path = '/path/to/page'
request = Request(base_url + relative_path, callback=my_callback)
请根据您的具体需求选择合适的方法进行网址拼接。