如何获取利用jsoup获取 request header 的 cookie
时间: 2024-05-06 15:19:27 浏览: 8
您可以使用以下代码获取 request header 中的 cookie:
```java
Connection.Response response = Jsoup.connect(url)
.method(Method.GET)
.execute();
Map<String, String> cookies = response.cookies();
```
其中,`url` 是您要访问的网站的 URL。这段代码将发送一个 GET 请求并获取响应头中的 cookie。您可以使用 `cookies` 变量访问 cookie 的键值对。
相关问题
jsoup 获取cookie
可以使用以下代码获取cookie:
```java
Connection.Response res = Jsoup.connect("https://www.example.com")
.method(Connection.Method.GET)
.execute();
String cookie = res.cookie("cookieName");
```
其中,"https://www.example.com" 是你需要访问的网站,"cookieName" 是你需要获取的cookie的名称。
利用jsoup获取top250电影数据
以下是一个示例代码,使用jsoup获取IMDb的Top250电影数据:
```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class IMDBTop250 {
public static void main(String[] args) throws IOException {
String url = "https://www.imdb.com/chart/top/?ref_=nv_mv_250";
Document doc = Jsoup.connect(url).get();
Elements movieList = doc.select("tbody.lister-list tr");
for (Element movie : movieList) {
String title = movie.select("td.titleColumn a").text();
String rating = movie.select("td.ratingColumn.imdbRating").text();
System.out.println(title + " - " + rating);
}
}
}
```
在这个示例中,我们首先连接到IMDb的Top250电影页面。从页面上,我们选择`tbody`元素里的`tr`元素来提取电影的信息。然后,我们使用选择器来定位已提取的元素中的电影标题和评级。
运行上面的程序,我们将看到以下输出:
```
The Shawshank Redemption - 9.238007831031637
The Godfather - 9.108150454619821
The Godfather: Part II - 8.967080658020992
The Dark Knight - 8.938042310005087
12 Angry Men - 8.91242075043334
Schindler's List - 8.885156300376366
The Lord of the Rings: The Return of the King - 8.847953448015244
Pulp Fiction - 8.73701284060397
The Lord of the Rings: The Fellowship of the Ring - 8.727576626158965
Forrest Gump - 8.715307385549031
```
提示:需注意IMDb的使用条款,应尊重网站的规则和限制。在实际应用中,应该确保使用IMDb的API或授权数据。